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
queryparam ofgeoNeardecides the number of docs examined.In your first case, it's considered as pipeline.
geoNearexecutes first thenmatchstage. Hence the number changes.