2017-04-14 106 views
2

我想創建一個新文檔,它從具有相同buyer的所有訂單中獲取所有cartItems。如果它沒有一對(像倫納德一樣),它會創建新的文檔,但狀態爲"orderId" : "merged"如何在一個文件中合併多個文件。 MongoDB

例如: 這是需要的情況下,當一些客戶會做出幾個不同的訂單,但我只需要給一個合併配方。

收藏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提供的例子。

+0

我想你應該嘗試的MongoDB聚集https://docs.mongodb.com/manual/reference/operator/aggregation/group/ –

回答

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的外殼,但它的JS)

+0

Thanx工作很好! –