I am using a $geoNear as the first step in the aggregation framework. I need to filter out the results based on "tag" field and it works fine but I see there are 2 ways both giving different results.
Sample MongoDB Document
{ "position": [ 40.80143, -73.96095 ], "tag": "pizza" }
I have added 2dsphere index to the "position" key
db.restaurants.createIndex( { 'position' : "2dsphere" } )
Query 1
db.restaurants.aggregate( [ { "$geoNear":{ "near": { type: "Point", coordinates: [ 55.8284,-4.207] }, "limit":100, "maxDistance":10*1000, "distanceField": "dist.calculated", "includeLocs": "dist.location", "distanceMultiplier":1/1000, "spherical": true } },{ "$match":{"tag":"pizza"} }, { "$group":{"_id":null,"totalDocs":{"$sum":1}} } ] );
Query 2
db.restaurants.aggregate( [ { "$geoNear":{ "query" : {"tag":"pizza"} "near": { type: "Point", coordinates: [ 55.8284,-4.207] }, "limit":100, "maxDistance":10*1000, "distanceField": "dist.calculated", "includeLocs": "dist.location", "distanceMultiplier":1/1000, "spherical": true } }, { "$group":{"_id":null,"totalDocs":{"$sum":1}} } ] );
The grouping option is just to get the count of documents returned by both the queries.
The totalDocs returned by both queries seem to be different.
Can someone explain me the differences between both the queries ?
Few assumptions:-
1. Assume there are 300 records that match based on the location.
2. Assume first set of 100 results do not have tag pizza. The rest 200 documents (101 to 300) have tag pizza
Query 1:-
Query 2:-
P.S : - The $group pipeline stage is added just for getting the count and hence have not written about it in the explaination