2

我有两个系列。让我们呼叫一个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"  
}]
4

2 回答 2

4

MongoDB 中没有“加入”。您可以:

  • 考虑使用 MapReduce 函数创建一个包含合并数据的新结构
  • fruit编写按需获取每个实例所需的代码,并将其与basket文档合并到您的客户端代码中。
  • 对数据进行非规范化并在文档中包含每个水果的详细信息basket。这带来了它自己的一系列问题,因为数据是重复的,fruit然后需要对集合中的每次使用进行更新。

两者都有其优点和缺点。

您可能会发现此Q/A以及MongoDB 文档很有帮助。

于 2013-04-08T16:49:46.683 回答
3

这不再是真的。

从 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 }
   ]
}
于 2020-01-10T00:20:45.987 回答