Mongodb 聚合查询以根据从另一个 collection 获得的列表获取数据

Mongodb aggregate query to get data based on a list obtained from another collection

我有两个collections。用户和客户

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

有一个用户名,我想从 Companies 中获取 Users 的列表,此用户是

的成员。

所以流程是这样的:

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 在一个查询中得到这个,但我失败得很惨努力让它发挥作用。

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