从另一个基于_id和merge的集合中获取信息 - MongoDB

时间:2013-04-08 14:32:28

标签: node.js mongodb aggregation-framework

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

2 个答案:

答案 0 :(得分:2)

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

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

两者都有其优点和缺点。

您可能会发现MongoDB的这个Q/A有用的文档以及this文档。

答案 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 }
   ]
}