How to update values in collection 1 with values in collection 2

I’m having two collections 1 & 2 and have similar fields (‘name’, ‘age’, ‘rank’) in both collections. How to update ‘age’ field values in collection 2 from ‘age’ field value in collection 1.

collection 1:
id name age rank
1 Jhon 12 7
2 Mery 15 2
3 Keva 14 1

collection 2:

id name age rank
5 Jack 17 4
1 Jhon ? 7
3 Keva ? 1


Expected Result:

collection 2:

  id  name  age rank
   5  Jack   17   4
   1  Jhon   12   7
   3  Keva   14   1

Hi @Aruna_Kumari and welcome in the MongoDB Community :muscle: !

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.

1 Like