我有两个系列。让我们拨打一个baskets
,另一个fruits
。
在baskets
我们有以下文件:
[{
basket_name: "John's Basket",
items_in_basket: [
{
fruit_id: 1,
comment: "Delicious!"
},
{
fruit_id: 2,
comment: "I did not like this"
}
]
}]
在fruits
我们有以下文件:
[{
_id: 1,
fruit_name: "Strawberry",
color: "Red"
},
{
_id: 2,
fruit_name: "Watermelon",
color: "Green"
}]
如何获取John's Basket
中每种水果的信息?
结果应如下所示:
[{
fruit_id: 1,
comment: "Delicious!",
fruit_name: "Strawberry",
color: "Red"
},
{
fruit_id: 2,
comment: "I did not like this",
fruit_name: "Watermelon",
color: "Green"
}]
答案 0 :(得分:2)
MongoDB中没有“加入”。你可以:
fruit
实例所需的代码,并使用basket
文档将其合并到客户端代码中。 basket
文档中包含每个水果的详细信息。这会带来一系列问题,因为数据是重复的,因此需要对集合中的每个用法进行特定fruit
的更新。两者都有其优点和缺点。
答案 1 :(得分:2)
这不再是事实。
从3.2版开始,MongoDB添加了$ 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"
}
}
])
返回:
{
"_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 }
]
}