javascript - How to merge multiple documents in one. MongoDB -


i want make new document, cartitems orders have same buyer. , if hasn't pair (like leonard) it's make new doc status "orderid" : "merged".

for example: it's needed situation, when customer make few different orders need give 1 consolidated recipe.

collection orders:

input { "_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 } output { "_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" }

would better if provide example in 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 }}]) 

btw, it's mongodb shell, it's js ;)


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -