I have 2 collections:
users
collection:
{
"_id": "1234141341"
"name": "David",
"is_active": True,
"age": 20
}
locations
collection:
{
"owner": "1234141341"
"type": "Point"
"coordinates": [ 105.843111, 21.045752 ]
}
I want to join users
collection with locations
collection. My query:
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"]},
},
},
],
}
}
)
For optimize this aggregrate query, I want to get list of user id after stage $match
, then pass this list of user id to stage $geoNear
of $lookup
for filter location that belong to filtered users. So this $geoNear
stage will not calculate all locations. I have read mongo document, also read questions in this site, but I can not find out the answer. Any idea about this is appreciated, thanks