Two $Geonear in aggrigate Mongo

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] } }
]

Upvotes: 4

Views: 231

Answers (1)

D. SM
D. SM

Reputation: 14530

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.

Upvotes: 0

Related Questions