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

To add a new property to each document in a large MongoDB collection, use the forEach() method combined with update() and $set operator. This approach iterates through all documents and adds the new field dynamically.

Syntax

db.collection.find().forEach(function(doc) {
    db.collection.update(
        {_id: doc._id},
        {$set: {newProperty: computedValue}}
    );
});

Create Sample Data

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

View Current Documents

db.addingNewPropertyDemo.find().pretty();
{
    "_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"
}

Add New Property to All Documents

Add a new property StudentNameInUpperCase that stores the uppercase version of StudentName ?

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

Verify the Result

db.addingNewPropertyDemo.find().pretty();
{
    "_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"
}

Key Points

  • Use forEach() to iterate through all documents in the collection
  • The $set operator adds new fields or updates existing ones
  • Access existing field values using dot notation within the function
  • For very large collections, consider using updateMany() with aggregation pipeline for better performance

Conclusion

The forEach() method combined with update() and $set effectively adds new properties to all documents in a collection. This approach allows you to compute new field values based on existing data in each document.

Updated on: 2026-03-15T00:41:29+05:30

885 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements