Set variable value in MongoDB save() method

To set a variable value in MongoDB's save() method, use db.collectionName.save(variableName) where variableName is your JavaScript variable containing the document data.

Syntax

var variableName = { field1: "value1", field2: "value2" };
db.collectionName.save(variableName);

Example

Let us create a variable with document data and save it to a collection ?

Step 1: Create a Variable

var Info = {
    "Name": "David",
    "CountryName": "US",
    "ProjectDetails": [
        {
            "ClientName": "David",
            "ProjectName": "Online Banking System"
        }
    ]
}

Step 2: Save Variable to Collection

db.demo483.save(Info);
WriteResult({ "nInserted" : 1 })

Step 3: Verify the Document

db.demo483.find().pretty();
{
    "_id" : ObjectId("5e82e0d6b0f3fa88e22790a0"),
    "Name" : "David",
    "CountryName" : "US",
    "ProjectDetails" : [
        {
            "ClientName" : "David",
            "ProjectName" : "Online Banking System"
        }
    ]
}

Key Points

  • Variables store document data as JavaScript objects before saving to MongoDB.
  • The save() method inserts new documents or updates existing ones based on the _id field.
  • MongoDB automatically generates an _id if not provided in the variable.

Conclusion

Using variables with save() method provides a clean way to store complex document structures in MongoDB. This approach is especially useful for documents with nested arrays and objects.

Updated on: 2026-03-15T03:07:53+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements