MongoDB:是否可以将 2 个请求合并为一个?



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

相关内容

  • 没有找到相关文章

最新更新