How to use save() correctly in MongoDB?

The save() method in MongoDB is used to insert a new document or update an existing document based on whether the document contains an _id field. If no _id is provided, it inserts a new document. If an _id exists, it updates the existing document.

Syntax

db.collection.save(document)

Create Sample Data

Let us create a collection with documents using save() ?

db.demo481.save({"FirstName":"Chris","LastName":"Brown"});
db.demo481.save({"FirstName":"David","LastName":"Miller"});
db.demo481.save({"FirstName":"John","LastName":"Doe"});
db.demo481.save({"FirstName":"John","LastName":"Smith"});
WriteResult({ "nInserted" : 1 })
WriteResult({ "nInserted" : 1 })
WriteResult({ "nInserted" : 1 })
WriteResult({ "nInserted" : 1 })

Display Documents

Display all documents from the collection using find() ?

db.demo481.find();
{ "_id" : ObjectId("5e82db39b0f3fa88e227909c"), "FirstName" : "Chris", "LastName" : "Brown" }
{ "_id" : ObjectId("5e82db45b0f3fa88e227909d"), "FirstName" : "David", "LastName" : "Miller" }
{ "_id" : ObjectId("5e82db4db0f3fa88e227909e"), "FirstName" : "John", "LastName" : "Doe" }
{ "_id" : ObjectId("5e82db52b0f3fa88e227909f"), "FirstName" : "John", "LastName" : "Smith" }

Example: Update Using save()

To update an existing document, include the _id field in the document ?

db.demo481.save({
    "_id" : ObjectId("5e82db39b0f3fa88e227909c"), 
    "FirstName" : "Chris", 
    "LastName" : "Johnson"
});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Key Points

  • Insert: If no _id is provided, save() creates a new document
  • Update: If _id exists, save() replaces the entire document
  • save() is deprecated in MongoDB 3.2+. Use insertOne(), updateOne(), or replaceOne() instead

Conclusion

The save() method provides a simple way to insert or update documents based on the _id field. However, modern MongoDB applications should use the newer, more explicit methods like insertOne() and updateOne() for better clarity and control.

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

489 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements