我使用$ geoNear作为聚合框架的第一步。我需要根据" tag"过滤掉结果。字段,它工作正常,但我发现有两种方法可以产生不同的结果。
示例MongoDB文档
{ "position": [ 40.80143, -73.96095 ], "tag": "pizza" }
我已将2dsphere索引添加到"位置"键
db.restaurants.createIndex( { 'position' : "2dsphere" } )
查询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}} } ] );
查询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}} } ] );
分组选项只是为了获取两个查询返回的文档数。
两个查询返回的totalDocs似乎不同。
有人可以解释一下这两个查询之间的区别吗?
答案 0 :(得分:2)
几个假设: -
1.假设有300条记录根据位置匹配。
2.假设第一组100个结果没有标签披萨。其余200个文件(101至300)具有标签披萨
查询1: -
查询2: -
P.S: - $ group管道阶段只是为了获得计数而被添加,因此在解释中没有写过它
答案 1 :(得分:0)
if you have to apply multiple creteria to find locations then this query might helpful
const userLocations = await userModel.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [data.lon1,data.lat1]
},//set the univercity points
spherical: true,
distanceField: "calcDistance",
// maxDistance: 2400,//25km
"distanceMultiplier": 0.001,
}
},
{ $unwind: "$location" },
{ $match: {
"location": {
$geoWithin: {
$centerSphere: [
[ 73.780553, 18.503327], 20/ 6378.1 //check the user point is present here
]
}
}
}},
])