我使用$ geoNear作为聚合框架的第一步 . 我需要根据“标签”字段过滤掉结果并且它工作正常,但我发现有两种方法都能给出不同的结果 .
Sample MongoDB Document
{
"position": [
40.80143,
-73.96095
],
"tag": "pizza"
}
我在“位置”键中添加了2dsphere索引
db.restaurants.createIndex( { 'position' : "2dsphere" } )
Query 1
使用$ match聚合管道操作根据“tag”键过滤掉结果
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
Uses query inside the $geoNear aggregation operation to filter results based on "tag" key
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}}
}
]
);
分组选项只是为了获取两个查询返回的文档数 .
两个查询返回的totalDocs似乎不同 .
有人可以解释我两个查询之间的差异吗?
2 回答
Few assumptions:-
1.假设有300条记录根据位置匹配 .
2.假设第一组100个结果没有标签披萨 . 其余200个文件(101至300)具有标签披萨
Query 1:-
有2个管道操作$ geoNear和$ match
$ geoNear管道操作的输出是$ match管道操作的输入
$ geoNear根据最近距离排序的位置查找最多100个结果(我们指定的限制) . (请注意,此处返回的100个结果完全基于位置 . 因此,这100个结果不包含任何带有标记"pizza"的文档)
这100个结果被发送到发生过滤的下一个管道操作$ match . 但由于第一组100个结果没有标签披萨,因此输出为空
Query 2:-
只有一个管道操作$ geoNear
$ geoNear管道操作中包含一个查询字段$ geoNear根据按最近距离排序的位置和查询标签= pizza查找最多100个结果(我们已指定的限制)
现在,101到200的结果将作为输出返回,因为查询包含在管道操作$ geoNear中 . 因此,在简单的句子中,我们说,找到位置为[x,y]的所有文件,标签为= pizza .
P.S: - $ group管道阶段只是为了获得计数而添加,因此在解释中没有写出来