gpt4 book ai didi

mongodb - $geoNear 匹配最近的数组

转载 作者:可可西里 更新时间:2023-11-01 09:13:26 24 4
gpt4 key购买 nike

我在记录集合 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"
}});

这个结果给了我距离场。现在你能在我的文档中解释一下这个多元素中存在哪个地址数组吗?我如何确定该结果对哪个元素为真?

另一个问题:- 如果我在“addresses.apporx”上设置大于或等于的条件,那么有没有办法找到这个条件的位置?

最佳答案

首先,如果您打算对现实世界坐标进行地理空间查询,我强烈建议您为您的收藏创建一个“2dsphere”索引。

确保删除您可能一直在使用的其他索引:

db.records.dropIndexes();
db.records.createIndex({ "addresses.loc": "2dsphere" })

为了做你想做的事,首先看一下对 $geoNear 也包括 includeLocs 选项的细微修改。

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
]
}

关于mongodb - $geoNear 匹配最近的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44280713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com