Reputation: 73
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.
Upvotes: 5
Views: 13351
Reputation: 3845
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
Upvotes: 16