我在记录集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“上设定了更大的条件或者等于的条件,那么有什么方法可以找到这个条件的位置吗?
发布于 2017-05-31 09:47:30
首先,我强烈建议您为您的集合创建一个"2dsphere“索引,如果您打算在现实世界坐标上进行地理空间查询的话。
请确保删除可能正在使用的其他索引:
db.records.dropIndexes();
db.records.createIndex({ "addresses.loc": "2dsphere" })为了做你想做的事情,首先看一下轻微的修改,其中还包括了includeLocs选项到$geoNear。
db.records.aggregate([
{ "$geoNear": {
"near": [ -73.9815103, 40.7475731 ],
"spherical": true,
"distanceField": "distance",
"includeLocs": "locs"
}}
])现在您将看到如下所示的输出:
{
"_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
]
}因此,返回的不仅仅是距离最近点的距离,还包括“哪个”位置是使用的匹配点。
因此,如果您想要$filter原始数组返回最近的数组,那么您可以:
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" ] }
}
}
}}
])并返回只有该匹配的数组:
{
"_id" : ObjectId("592d0c78555a7436b0883960"),
"userid" : 7,
"addresses" : [
{
"apporx" : 50,
"loc" : [
-73.98137109999999,
40.7476039
]
}
],
"distance" : 0.0000019174641401278624,
"locs" : [
-73.98137109999999,
40.7476039
]
}https://stackoverflow.com/questions/44280713
复制相似问题