Hi @Aruna_Kumari and welcome in the MongoDB Community
!
Assuming the _id
in each doc represents the same unique user in both collections, we can use the “$merge” aggregation stage to update coll2
.
db.coll1.insertMany([{_id:1, name:"Jhon", age:12, rank:7},{_id:2, name:"Mery", age:15, rank:2}, {_id:3, name:"Keva", age:14, rank:1}])
db.coll2.insertMany([{_id:5, name:"Jack", age:17, rank:4},{_id:1, name:"Jhon", rank:7}, {_id:3, name:"Keva", rank:1}])
test [direct: primary] test> db.coll1.find()
[
{ _id: 1, name: 'Jhon', age: 12, rank: 7 },
{ _id: 2, name: 'Mery', age: 15, rank: 2 },
{ _id: 3, name: 'Keva', age: 14, rank: 1 }
]
test [direct: primary] test> db.coll2.find()
[
{ _id: 5, name: 'Jack', age: 17, rank: 4 },
{ _id: 1, name: 'Jhon', rank: 7 },
{ _id: 3, name: 'Keva', rank: 1 }
]
Here is the aggregation I can apply on coll1
:
[
{
'$project': {
'age': 1
}
}, {
'$merge': {
'into': 'coll2',
'on': '_id',
'whenMatched': 'merge',
'whenNotMatched': 'discard'
}
}
]
Here is the result:
test [direct: primary] test> db.coll1.aggregate([
... {
..... '$project': {
....... 'age': 1
....... }
..... }, {
..... '$merge': {
....... 'into': 'coll2',
....... 'on': '_id',
....... 'whenMatched': 'merge',
....... 'whenNotMatched': 'discard'
....... }
..... }
... ])
test [direct: primary] test> db.coll2.find()
[
{ _id: 5, name: 'Jack', age: 17, rank: 4 },
{ _id: 1, name: 'Jhon', rank: 7, age: 12 },
{ _id: 3, name: 'Keva', rank: 1, age: 14 }
]
Cheers,
Maxime.
PS : It’s weird to have two very similar collections like this that contains the same data.