3

The collection has two geo fields: fromLocation and toLocation. But only one Geonear is allowed. The collection looks like:

...............
 fromLocation: {
    type: { type: String, default: "Point" },
    coordinates: [Number],
  },
  toLocation: {
    type: { type: String, default: "Point" },
    coordinates: [Number],
  },
.........................................

plese give example code, how to use Geonear for search by two fields. My code for one field search:

[
  {
    '$geoNear': {
      near: [Object],
      key: 'fromLocation',
      distanceField: 'fromDistance',
      spherical: true
    }
  },
  {
    '$match': {
      status: 2,
      'from.data.city_fias_id': '27c5bc66-61bf-4a17-b0cd-ca0eb64192d6',
      'to.data.city_fias_id': '27c5bc66-61bf-4a17-b0cd-ca0eb64192d6',
      'car.paymentInfo.id': [Object],
      budget: [Object]
    }
  },
  {
    '$lookup': {
      from: 'users',
      localField: 'autor',
      foreignField: '_id',
      as: 'autor'
    }
  },
  { '$unwind': '$autor' },
  { '$addFields': { sortBudget: [Object] } },
  { '$sort': { sortBudget: 1 } },
  { '$group': { _id: null, total: [Object], results: [Object] } },
  { '$project': { total: 1, results: [Object] } }
]
  • Dear Egor, welcome to Stackoverflow. Please get yourself familiar with https://stackoverflow.com/help/how-to-ask. "Please help" is not a problem statement. It's not quite clear what help you expect. $geoNear can be used only on the first stage of the pipeline and each pipeline has exactly 1 first stage. Try to rephrase your question. Add some examples - a few stripped down documents and what you expect in the result. If you have tried anything - add your attempts as well. – Alex Blex Aug 14 '20 at 09:36

1 Answers1

0

Distance calculation is rather straightforward. Use $geoNear for the more selective condition to take advantage of the geo index, use $match and $expr for the second condition.

D. SM
  • 13,584
  • 3
  • 12
  • 21