Search code examples
jsonmongodbgeolocationmongodb-query

Multiple $near in mongo 2.6.4 does not work


I have collection with document like this:

{
  ...
  "CurrentLocation" : {
    "type" : "Point",
    "coordinates" : [ 
        -92.48436693078111, 
        35.85223020932276
    ]
  }
  ...
}

And I need to make a "$near" query with two possible center points:

db.Truck.find({
    "$or": [{
        "DestinationLocation": {
            "$near": {
                "$geometry": {
                    "type": "Point",
                    "coordinates": [-117.256875, 41.856405]
                },
                "$maxDistance": 100000.0
            }
        }
    }, {
        "DestinationLocation": {
            "$near": {
                "$geometry": {
                    "type": "Point",
                    "coordinates": [-112.256875, 40.856405]
                },
                "$maxDistance": 100000.0
            }
        }
    }]
})

Mongo returns me an error:

error:
{
"$err" : "Can't canonicalize query: BadValue Too many geoNear expressions",
"code" : 17287
}

Is there any way to request $near with two points except data union on the application side? Thanks.


Solution

  • Mongo DB accepts only one NEAR. And if there is a NEAR, it must be either the root or the root must be an AND and its child must be a NEAR. See https://github.com/mongodb/mongo/blob/master/src/mongo/db/query/canonical_query.cpp#L364

    If you need that $or operation with two $near, try to make two queries and integrate the results from them.