我有两个收藏。用户和客户端
Companies
:
{"_id":{"$oid":"599d8864a5304114ac9b8a0a"},"id":"company1","name":"Big Company", "users":["Jack", "Martin"]}
{"_id":{"$oid":"599d8864a5304114ac9b8a0b"},"id":"company2","name":"Super Big Company", "users":["Kate", "Jack"]}
Users
:
{"_id":{"$oid":"59b0178ca5304101c1a99711"},"username":"Jack","hashedPassword":"2f1f147e358f28a74cd29c7f44eedd4ec0293d6c"},
{"_id":{"$oid":"59b0178ca5304101c1a99811"},"username":"Martin","hashedPassword":"1f5f147e358f21a74cd29c7f44eedd4ec0293d6c"}
拥有一个用户名,我想从该用户所属的Users
中获得Companies
的列表。
所以流程如下:
Find all companies which have Jack in the list of their users -> extract and join arrays -> Return the list of User objects with matching username from the array
我知道应该可以使用 aggregate 函数和 $ lookup 在一个查询中获得此查询,但是我不幸地使它无法正常工作。
>答案 0 :(得分:0)
db.Clients.aggregate([
{
"$lookup":
{
"from": "Users",
"localField": "users",
"foreignField": "username",
"as": "user_details"
}
},
{"$match": {"users":"Jack"}},
{"$unwind": "$user_details" },
{"$project": {"user_details" :1,"_id":0}}
])