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
Update only a single MongoDB document without deleting any date
To update only a single document in MongoDB, use the updateOne() method. This method updates the first document that matches the specified filter criteria and preserves all existing data except for the fields being updated.
Syntax
db.collection.updateOne(
{ "field": "matchValue" },
{ $set: { "fieldToUpdate": "newValue" } }
);
Create Sample Data
Let us create a collection with documents ?
db.demo495.insertMany([
{"FirstName":"Chris","Age":19},
{"FirstName":"David","Age":21},
{"FirstName":"Bob","Age":26},
{"FirstName":"John","Age":22}
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5e84adfeb0f3fa88e22790ca"),
ObjectId("5e84ae05b0f3fa88e22790cb"),
ObjectId("5e84ae0eb0f3fa88e22790cc"),
ObjectId("5e84ae15b0f3fa88e22790cd")
]
}
Display all documents from the collection ?
db.demo495.find();
{ "_id" : ObjectId("5e84adfeb0f3fa88e22790ca"), "FirstName" : "Chris", "Age" : 19 }
{ "_id" : ObjectId("5e84ae05b0f3fa88e22790cb"), "FirstName" : "David", "Age" : 21 }
{ "_id" : ObjectId("5e84ae0eb0f3fa88e22790cc"), "FirstName" : "Bob", "Age" : 26 }
{ "_id" : ObjectId("5e84ae15b0f3fa88e22790cd"), "FirstName" : "John", "Age" : 22 }
Example: Update Single Document
Update David's age from 21 to 23 ?
db.demo495.updateOne(
{"FirstName":"David"},
{$set: {"Age":23}}
);
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Verify Result
Display all documents to verify the update ?
db.demo495.find();
{ "_id" : ObjectId("5e84adfeb0f3fa88e22790ca"), "FirstName" : "Chris", "Age" : 19 }
{ "_id" : ObjectId("5e84ae05b0f3fa88e22790cb"), "FirstName" : "David", "Age" : 23 }
{ "_id" : ObjectId("5e84ae0eb0f3fa88e22790cc"), "FirstName" : "Bob", "Age" : 26 }
{ "_id" : ObjectId("5e84ae15b0f3fa88e22790cd"), "FirstName" : "John", "Age" : 22 }
Key Points
-
updateOne()updates only the first document that matches the filter - Uses
$setoperator to modify specific fields without affecting other data - Returns acknowledgment with
matchedCountandmodifiedCount
Conclusion
The updateOne() method safely updates a single document while preserving all existing fields. It's ideal when you need to modify specific data without affecting multiple documents or deleting any information.
Advertisements
