我有 2 个收藏:
users
收藏:
{
"_id": "1234141341"
"name": "David",
"is_active": True,
"age": 20
}
locations
收藏:
{
"owner": "1234141341"
"type": "Point"
"coordinates": [ 105.843111, 21.045752 ]
}
我想加入users
收藏与locations
收藏。我的查询:
db.collection.aggregrate(
{
"$match": {
"is_active": True,
}
},
{
"$lookup": {
"from": "locations",
"as": "location",
"let": {"user_id": "$_id", "list_user_id": "the expression to get list of user id after $match stage"},
"pipeline": [
{
"$geoNear": {
"near": {"type": "Point", "coordinates": [ 105.843111, 21.045752 ]},
"distanceField": "distance",
"query": {
// "owner": {"$in": "$$list_user_id"} // <---- filter location that belong filtered user here
},
}
},
{
"$redact": {
"$cond": {
"if": {"$lte": ["$distance", 10000000000]},
"then": "$$KEEP",
"else": "$$PRUNE",
}
}
},
{
"$match": {
"$expr": {"$eq": ["$owner", "$$user_id"]},
},
},
],
}
}
)
为了优化这个聚合查询,我想在 stage 之后获取用户 id 列表$match
,然后将此用户 id 列表传递到属于过滤用户的过滤器位置$geoNear
的阶段。$lookup
所以这个$geoNear
阶段不会计算所有的位置。我已经阅读了 mongo 文档,也阅读了这个站点中的问题,但我找不到答案。对此的任何想法表示赞赏,谢谢