Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
_idis provided,save()creates a new document -
Update: If
_idexists,save()replaces the entire document -
save()is deprecated in MongoDB 3.2+. UseinsertOne(),updateOne(), orreplaceOne()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.
Advertisements
