我想制作一个新文档,它从所有具有相同buyer的订单中获取所有cartitem。如果它没有一对(像伦纳德那样),它会生成新的doc,但状态是"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}
如果你在js中提供示例会更好。

最佳答案

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;)

08-07 16:45