如何将多个文档合并为一个。 MongoDB的

时间:2017-04-14 12:54:30

标签: javascript mongodb

我想创建一个新文档,该文档从所有具有相同buyer的订单中获取所有cartItem。如果它没有一对(就像伦纳德一样)它会创建新的文档,但状态为"orderId" : "merged"

例如: 这是需要的情况,当一些客户将做出几个不同的订单,但我只需要给出一个合并的配方。

收藏orders

输入 { "_id" : "001", "buyer": "Sheldon" "cartItems" : [ { "itemName" : "Water", "itemPrice" : 3 } ], "totalCost" : 3 }, { "_id" : "002", "buyer" : "Sheldon", "cartItems" : [ { "itemName" : "Milk", "itemPrice" : 2 } ], "totalCost" : 2 }, { "_id" : "003", "buyer" : "Sheldon", "cartItems" : [ { "itemName" : "Butter", "itemPrice" : 4 } ], "totalCost" : 4 }, { "_id" : "004", "buyer" : "Leonard", "cartItems" : [ { "itemName" : "Water", "itemPrice" : 3 } ], "totalCost" : 3 } 输出 { "_id" : "003_new", "buyer" : "Sheldon", "cartItems" : [ { "itemName" : "Water", "itemPrice" : 3 }, { "itemName" : "Milk", "itemPrice" : 2 }, { "itemName" : "Butter", "itemPrice" : 4 } ], "totalCost" : 9, "orderId" : "merged" }, { "_id" : "004_new", "buyer" : "Leonard", "cartItems" : [ { "itemName" : "Water", "itemPrice" : 3 } ], "totalCost" : 3, "orderId" : "merged" }

如果你在JS中提供示例,会更好。

1 个答案:

答案 0 :(得分:1)

db.orders.aggregate([
    {$sort: {_id: 1, buyer: 1}},
    {$unwind: '$cartItems'},
    {$group: {_id: '$buyer', cartItems: {$push: '$cartItems'},
        totalCost: {$sum: '$totalCost'},
        id: {$last: {$concat: ["$_id", "_", "new" ]}},
        buyer: {$last: '$buyer'}}},
    {$addFields: {orderId: 'merged', _id: '$id'}},
    {$project: {"id": 0 }}])
顺便说一下,这是mongodb shell,但它是JS;)