简体   繁体   中英

How to merge multiple documents in one. MongoDB

I want to make a new document, which get all cartItems from all orders which have the same buyer . And if it hasn't a pair (like with Leonard) it's make new doc but with status "orderId" : "merged" .

For example: It's needed for situation, when some customer will make few different orders but I need to give only one 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 be better if you 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, but it's JS ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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