【发布时间】:2020-06-09 18:45:50
【问题描述】:
这是我的收藏模型:
db={
"user": [
{
"_id": ObjectId("5ed5525d98980326b5505c0a"),
"friends": [
{
"friend_id": ObjectId("5ed54c3d98980326b5505ad2")
},
]
},
{
"_id": ObjectId("5ed54c3d98980326b5505ad2"),
"friends": []
}
],
"geo": [
{
"_id": ObjectId("5ed54e6a98980326b5505b4b"),
"user_id": ObjectId("5ed54c3d98980326b5505ad2"),
"location": {
"type": "Point",
"coordinates": [
58.631576,
49.614203
]
}
}
]
}
我的任务是编写一个聚合来获取所有距离小于 400 米的朋友。我的聚合:
db.users.aggregate([
{
$project: {
"friends": 1
}
},
{
$lookup: {
from: "geo",
localField: "_id",
foreignField: "user_id",
as: "my_geo"
}
},
{
$unwind: "$my_geo"
},
{
$lookup: {
from: "geo",
let: {
"loc": "$my_geo.location.coordinates",
"uid": "$_id"
},
pipeline: [
{
$geoNear: {
near: "$$loc",
distanceField: "dist.calculated",
spherical: false,
maxDistanse : 400
}
}
],
as: "us_geo"
}
}
])
不幸的是,$geoNear 中的near 字段需要一个数组,并且不想接受$$loc。
在第一步中,我得到了我的地理位置,在将$lookup 与 pipline 一起使用后,我想得到我所有朋友的地理位置,距离不超过 400 米。也许你会建议另一种数据存储模型,我不太喜欢,但我希望你能帮助完成聚合。
我坐了很长时间,向专家寻求帮助。
我已经尝试了很多不同的方法,甚至谷歌也没有帮助我(
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework