简体   繁体   中英

Mongodb geospacial aggregate returns different results using $match vs query

db.units.aggregate([
  {
    "$geoNear": {
      "near": {
        "type": "Point",
        "coordinates": [ -3.70256, 40.4165 ]
      },
      "distanceField": "dist.calculated",
      "spherical": true,
      "maxDistance": 50000
    }
  },
  {
    $match: {
      "some.field.a": true,
      "otherField": null
    }
  }
]).explain("executionStats");

Gives me:

nReturned: 671,
          executionTimeMillis: 8,
          totalKeysExamined: 770,
          totalDocsExamined: 671,

However:

db.units.aggregate([
  {
    "$geoNear": {
      "near": {
        "type": "Point",
        "coordinates": [ -3.70256, 40.4165 ]
      },
      "distanceField": "dist.calculated",
      "spherical": true,
      "maxDistance": 50000,
      "query": {
        "some.field.a": true,
        "otherField": null
      }
    }
  }
]).explain("executionStats");

Gives me:

 nReturned: 67,
          executionTimeMillis: 6,
          totalKeysExamined: 770,
          totalDocsExamined: 1342,

The first question which comes to my mind is, why the number of returned documents is different? The second one is, why the totalDocsExamined is higher when using query of $geoNear ?

Updated When query field of $geoNear is used, there is a COLLSCAN to find all documents matching the query filter. Unless you create a compound index with all fields: db.units.createIndex({coordinates:'2dsphere', 'some.field.': 1, otherField:1 )

So it seems like the behavior in case of using query is by default a COLLSCAN except if you have a compounded index with the geospatial field plus the ones included in query .

Reason is that query param of geoNear decides the number of docs examined.

Limits the results to the documents that match the query. The query syntax is the usual MongoDB read operation query syntax.

In your first case, it's considered as pipeline. geoNear executes first then match stage. Hence the number changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM