Update MongoDB field using value of another field?


You can use aggregate function to update MongoDB field using the value of another field. Here, we will create two collections:

  • name

  • studentInformation

<name> Collection

The query to create first collection with documents is as follows:

> db.name.insert({"FirstName":"John","LastName":"Smith"});
WriteResult({ "nInserted" : 1 })

Now you can display all documents from the collection with the help of find() method. The query is as follows:

> db.name.find().pretty();

The following is the output that displays the collection “name” documents:

{
   "_id" : ObjectId("5c6c00dd68174aae23f5ef55"),
   "FirstName" : "John",
   "LastName" : "Smith"
}

<studentInformation> Collection

The query to create second collection with documents is as follows:

> db.studentInformation.insert({"StudentFirstName":"Carol","StudentLastName":"Taylor"});
WriteResult({ "nInserted" : 1 })

Now you can display all documents from the collection with the help of find() method. The query is as follows:

> db.studentInformation.find().pretty();

The following is the output:

{
   "_id" : ObjectId("5c6c013068174aae23f5ef56"),
   "StudentFirstName" : "Carol",
   "StudentLastName" : "Taylor"
}

Now, let us update collection “name” with another collection “studentInformation”. The query is as follows:

> db.studentInformation.aggregate( [
   {"$addFields":{"FullName":{"$concat":["$StudentFirstName"," ","$StudentLastName"]} }},
   {"$out":"name"} ] );

Now you can check the documents of the collection “name”. The query is as follows:

> db.name.find().pretty();

The following is the output that displays that we have successfully updated the fields:

{
   "_id" : ObjectId("5c6c013068174aae23f5ef56"),
   "StudentFirstName" : "Carol",
   "StudentLastName" : "Taylor",
   "FullName" : "Carol Taylor"
}

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements