How to use custom variable while updating a MongoDB document?

To use custom variables while updating MongoDB documents, first declare a variable with var, then reference it in your update() operation. This allows for dynamic updates and better code reusability.

Syntax

var variableName = yourValue;
db.collectionName.update(
    { filter },
    { $set: { fieldName: variableName } }
);

Create Sample Data

db.demo600.insertMany([
    { id: 1, Name: "Robert" },
    { id: 2, Name: "Mike" },
    { id: 3, Name: "Sam" }
]);
{
   "acknowledged" : true,
   "insertedIds" : [
      ObjectId("5e94a063f5f1e70e134e2699"),
      ObjectId("5e94a06bf5f1e70e134e269a"),
      ObjectId("5e94a072f5f1e70e134e269b")
   ]
}

Display all documents from the collection ?

db.demo600.find();
{ "_id" : ObjectId("5e94a063f5f1e70e134e2699"), "id" : 1, "Name" : "Robert" }
{ "_id" : ObjectId("5e94a06bf5f1e70e134e269a"), "id" : 2, "Name" : "Mike" }
{ "_id" : ObjectId("5e94a072f5f1e70e134e269b"), "id" : 3, "Name" : "Sam" }

Example: Using Custom Variable to Update Document

Create a custom variable and use it to update Mike's name to David ?

var replaceName = "David";
db.demo600.update(
    { id: 2 },
    { $set: { Name: replaceName } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Verify the update ?

db.demo600.find();
{ "_id" : ObjectId("5e94a063f5f1e70e134e2699"), "id" : 1, "Name" : "Robert" }
{ "_id" : ObjectId("5e94a06bf5f1e70e134e269a"), "id" : 2, "Name" : "David" }
{ "_id" : ObjectId("5e94a072f5f1e70e134e269b"), "id" : 3, "Name" : "Sam" }

Key Points

  • Variables are declared using var keyword in MongoDB shell.
  • Custom variables can store strings, numbers, objects, or arrays for reuse.
  • Variables remain accessible throughout the current shell session.

Conclusion

Custom variables in MongoDB provide flexibility for dynamic updates and reduce code repetition. Simply declare variables with var and reference them in your update operations for cleaner, more maintainable queries.

Updated on: 2026-03-15T03:47:35+05:30

524 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements