繁体   English   中英

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

[英]Get info from another collection based of _id and merge - MongoDB

我有两个收藏。 让我们称一个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"  
}]

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

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

两者都有其优点和缺点。

你可能会发现这个Q/A很有帮助,还有这个MongoDB 的文档。

这不再是事实。

从 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 }
   ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM