Adding new property to each document in a large MongoDB collection?


You can use update command along with forEach() for large collection. Let us first create a collection with documents

>db.addingNewPropertyDemo.insertOne({"StudentName":"John","StudentAge":23,"CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca1e61866324ffac2a7dc56")
}
>db.addingNewPropertyDemo.insertOne({"StudentName":"David","StudentAge":21,"CountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca1e62366324ffac2a7dc57")
}
>db.addingNewPropertyDemo.insertOne({"StudentName":"Bob","StudentAge":21,"CountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca1e62d66324ffac2a7dc58")
}

Following is the query to display all documents from a collection with the help of find() method

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

This will produce the following output

{
   "_id" : ObjectId("5ca1e61866324ffac2a7dc56"),
   "StudentName" : "John",
   "StudentAge" : 23,
   "CountryName" : "US"
}
{
   "_id" : ObjectId("5ca1e62366324ffac2a7dc57"),
   "StudentName" : "David",
   "StudentAge" : 21,
   "CountryName" : "AUS"
}
{
   "_id" : ObjectId("5ca1e62d66324ffac2a7dc58"),
   "StudentName" : "Bob",
   "StudentAge" : 21,
   "CountryName" : "UK"
}

Following is the query to add new property to each document in a large collection

> db.addingNewPropertyDemo.find().forEach(function(data){ db.addingNewPropertyDemo.update({_id: data._id}, {$set: { StudentNameInUpperCase: data.StudentName.toUpperCase() }}) });

Let us check a new property is added or not

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

Following is the output displaying the new property as well

{
   "_id" : ObjectId("5ca1e61866324ffac2a7dc56"),
   "StudentName" : "John",
   "StudentAge" : 23,
   "CountryName" : "US",
   "StudentNameInUpperCase" : "JOHN"
}
{
   "_id" : ObjectId("5ca1e62366324ffac2a7dc57"),
   "StudentName" : "David",
   "StudentAge" : 21,
   "CountryName" : "AUS",
   "StudentNameInUpperCase" : "DAVID"
}
{
   "_id" : ObjectId("5ca1e62d66324ffac2a7dc58"),
   "StudentName" : "Bob",
   "StudentAge" : 21,
   "CountryName" : "UK",
   "StudentNameInUpperCase" : "BOB"
}

Look at the above sample output, StudentNameInUpperCase property is added.

Updated on: 30-Jul-2019

622 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements