2 我有的集合:
Users
:
{
_id: "user_unique_id_123",
email: "user@google.com"
}
和Products
:
{
_id: "unique_product_id",
name: "product name",
user: "user_unique_id_123"
}
作为输入参数,我收到一个email address
,我需要提取与该email address
关联的所有Products
。
问题是,更好的方法只是向MongoDB发出one
请求,而不是2个单独的请求: 通过email
提取user Id
,提取后通过user-id
提取Products
。
那么,您能否建议一下,是否可以只有一个电话而不是两个电话?
你可以这样做
玩
db.Users.aggregate([
{
"$lookup": {
"from": "Products",
"localField": "_id",
"foreignField": "user",
"as": "userProducts"
}
}
])
{"$lookup":
{
"from": "collection to join",
"localField": "field from the input documents",
"foreignField": "field from the documents of the from collection",
"as": "output array field"
}