我的记录集Mongodb(3.4)中的文档如下: -
{
"_id" : ObjectId("592d0c78555a7436b0883960"),
"userid" : 7,
"addresses" : [
{
"apporx" : 50.0,
"loc" : [
-73.98137109999999,
40.7476039
]
},
{
"apporx" : 15.0,
"loc" : [
-73.982002,
40.74767
]
},
{
"apporx" :10.0,
"loc" : [
-73.9819567,
40.7471609
]
}
]
}
`
I created index on this collection using below query :-
`db.records.createIndex({'addresses.loc':1})`
when i execute my below query :-
`db.records.aggregate(
{$geoNear : {
near : [ -73.9815103, 40.7475731 ],
distanceField: "distance"
}});
这个结果给了我距离field.now你能在我的文档中解释一下这个多元素中存在哪个地址数组。我怎样才能确定这个结果的真实性?
另一个问题: - 如果我对“addresses.apporx”的条件大于或等于那么有没有办法找到这个条件的位置?
答案 0 :(得分:3)
首先,如果您打算在真实世界坐标上进行地理空间查询,我强烈建议您为集合创建“2dsphere”索引。
确保删除您可能正在玩的其他索引:
<hr class="line">
为了做你想做的事,首先看一下稍微修改,其中还包括$geoNear
的 includeLocs 选项
db.records.dropIndexes();
db.records.createIndex({ "addresses.loc": "2dsphere" })
现在您将看到如下所示的输出:
db.records.aggregate([
{ "$geoNear": {
"near": [ -73.9815103, 40.7475731 ],
"spherical": true,
"distanceField": "distance",
"includeLocs": "locs"
}}
])
所以返回的不仅是距离最近的点的距离,而是“哪个”位置是所使用的匹配。
因此,如果您想要$filter
原始数组返回最近的数组,那么您可以:
{
"_id" : ObjectId("592d0c78555a7436b0883960"),
"userid" : 7,
"addresses" : [
{
"apporx" : 50,
"loc" : [
-73.98137109999999,
40.7476039
]
},
{
"apporx" : 15,
"loc" : [
-73.982002,
40.74767
]
},
{
"apporx" : 10,
"loc" : [
-73.9819567,
40.7471609
]
}
],
"distance" : 0.0000019174641401278624,
"locs" : [
-73.98137109999999,
40.7476039
]
}
并返回仅包含该匹配的数组:
db.records.aggregate([
{ "$geoNear": {
"near": [ -73.9815103, 40.7475731 ],
"spherical": true,
"distanceField": "distance",
"includeLocs": "locs"
}},
{ "$addFields": {
"addresses": {
"$filter": {
"input": "$addresses",
"as": "address",
"cond": { "$eq": [ "$$address.loc", "$locs" ] }
}
}
}}
])