How to use custom variable while updating a MongoDB document?


To update, use update() and following is the syntax to create and use a sample custom variable −

var anyVariableName=yourValue;
db.yourCollectionName.update({filter},{$set:{yourFieldName:yourVariableName}});

Let us create a collection with documents −

> db.demo600.insertOne({id:1,Name:"Robert"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e94a063f5f1e70e134e2699")
}
> db.demo600.insertOne({id:2,Name:"Mike"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e94a06bf5f1e70e134e269a")
}
> db.demo600.insertOne({id:3,Name:"Sam"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e94a072f5f1e70e134e269b")
}

Display all documents from a collection with the help of find() method −

> db.demo600.find();

This will produce the following output −

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

Following is the query to use custom variable while updating a MongoDB document −

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

Display all documents from a collection with the help of find() method −

> db.demo600.find();

This will produce the following output −

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

Updated on: 15-May-2020

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements