[英]Get info from another collection based of _id and merge - MongoDB
I have two collections.我有两个收藏。 Lets call one
baskets
and the other one fruits
.让我们称一个
baskets
和另一个fruits
。
In baskets
we have the following document:在
baskets
我们有以下文件:
[{
basket_name: "John's Basket",
items_in_basket: [
{
fruit_id: 1,
comment: "Delicious!"
},
{
fruit_id: 2,
comment: "I did not like this"
}
]
}]
And in fruits
we have the following documents:在
fruits
我们有以下文件:
[{
_id: 1,
fruit_name: "Strawberry",
color: "Red"
},
{
_id: 2,
fruit_name: "Watermelon",
color: "Green"
}]
How do I get information on each fruit in John's Basket
?如何获取
John's Basket
每种水果的信息?
The result should look like this:结果应如下所示:
[{
fruit_id: 1,
comment: "Delicious!",
fruit_name: "Strawberry",
color: "Red"
},
{
fruit_id: 2,
comment: "I did not like this",
fruit_name: "Watermelon",
color: "Green"
}]
There's no "join" in MongoDB. MongoDB 中没有“加入”。 You either could:
你可以:
fruit
instance on demand and merge it in your client code with a basket
document.fruit
实例所需的代码,并将其与basket
文档合并到您的客户端代码中。basket
document.basket
文档中包含每个水果的详细信息。 This poses it's own set of issues as data is duplicated and updates to a particular fruit
would then need to be made to every usage in the collection.fruit
更新。 Both have their pros and cons.两者都有其优点和缺点。
You might find this Q/A helpful, and also this documentation for MongoDB.你可能会发现这个Q/A很有帮助,还有这个MongoDB 的文档。
this is no longer true.这不再是事实。
Since version 3.2, MongoDB added the $lookup command.从 3.2 版开始,MongoDB 添加了 $lookup 命令。
https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
db.orders.insert([
{ "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
{ "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 },
{ "_id" : 3 }
])
db.inventory.insert([
{ "_id" : 1, "sku" : "almonds", description: "product 1", "instock" : 120 },
{ "_id" : 2, "sku" : "bread", description: "product 2", "instock" : 80 },
{ "_id" : 3, "sku" : "cashews", description: "product 3", "instock" : 60 },
{ "_id" : 4, "sku" : "pecans", description: "product 4", "instock" : 70 },
{ "_id" : 5, "sku" : null, description: "Incomplete" },
{ "_id" : 6 }
])
db.orders.aggregate([
{
$lookup:
{
from: "inventory",
localField: "item",
foreignField: "sku",
as: "inventory_docs"
}
}
])
returns:返回:
{
"_id" : 1,
"item" : "almonds",
"price" : 12,
"quantity" : 2,
"inventory_docs" : [
{ "_id" : 1, "sku" : "almonds", "description" : "product 1", "instock" : 120 }
]
}
{
"_id" : 2,
"item" : "pecans",
"price" : 20,
"quantity" : 1,
"inventory_docs" : [
{ "_id" : 4, "sku" : "pecans", "description" : "product 4", "instock" : 70 }
]
}
{
"_id" : 3,
"inventory_docs" : [
{ "_id" : 5, "sku" : null, "description" : "Incomplete" },
{ "_id" : 6 }
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.