Mongo: aggregate $geoNear and $text no results

2019-02-20 03:13发布

问题:

I'm trying to do a geoNear + text search aggregate query in Mongoose:

landmarkSchema.aggregate(
   [
      { "$geoNear": {
        "near": {
          "type": "Point",
          "coordinates": [parseFloat(userCoord1), parseFloat(userCoord0)]
        },
        "distanceField": "distance",
        "minDistance": 1,
        "maxDistance": 5000,
        "spherical": true,
        "query": { "loc.type": "Point" }
      } },
      { $match: { $text: { $search: sText } } },
      { $sort: { score: { $meta: "textScore" } } }

  ],
  function(err,data) {
    if (data){
      res.send(data);
    }
    else {
        console.log('no results');
        res.send({err:'no results'});            
    }
});

But Mongo is not returning any results. When I perform each query separately, $geoNear and $match : $text the correct results are returned. Am I chaining the query incorrectly?

回答1:

Only an initial $match stage can use an index, so you cannot use a text index in the second $match. You also can't combine using a 2dsphere index and using a text index in the same $match. One option is switching the order of the text search $match stage and the $geoNear stage. Swapped, the text search will use a text index and $geoNear will still work if you set spherical : false. $geoNear will calculate planar, not spherical, distances, and will not use an index.

If that's not feasible, we could try to think of other options if you describe the use case.



回答2:

Alternatively to @wdberkeley's answer, you can use $geoWithin instead of the $geoNear stage.

db.landmarkSchema.aggregate([
  {$match: {
      $text: {$search: "great test text"} ,
      loc: {$geoWithin: {$centerSphere: [[ 14.3, 48.3], 5/6731]}}
  }}])

Note: The geo index won't be used!

More information: http://docs.mongodb.org/manual/reference/operator/query/geoWithin/