简体   繁体   中英

How can I merge two documents in MongoDB

I have two documents in one collection.

{id: 1, list_data: [1, 2, 4, 5]}
{id: 1, list_data: [2, 5, 8, 9]}

I want merge those data into one document.

{id: 1, list_data: [1, 2, 4, 5, 8, 9]}

How can I do this job? Please help me. Thanks.

According to MongoDB documentation

Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result.

Please refer the aggregation query as mentioned below .

db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $unwind: {
                path:'$list_data'
            }
        },

        // Stage 2
        {
            $group: {
              _id:{id:'$id'},
              list_data:{$addToSet:'$list_data'}
            }
        },

        // Stage 3
        {
            $project: {
                '_id.id':1,
                "list_data":1
            }
        },

    ]



);

In above query document is processed through multiple stages of aggregation pipeline

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