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 document in MongoDB
To update only a single document in MongoDB, use the updateOne() method. This method updates the first document that matches the query criteria, even if multiple documents match the filter condition.
Syntax
db.collection.updateOne(
{ filter },
{ $set: { field: "newValue" } }
);
Sample Data
Let us first create a collection with documents ?
db.updateOneDemo.insertMany([
{"StudentId": 1, "StudentFirstName": "Chris"},
{"StudentId": 2, "StudentFirstName": "David"},
{"StudentId": 1, "StudentFirstName": "Mike"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e06ed3725ddae1f53b621e8"),
ObjectId("5e06ed3825ddae1f53b621e9"),
ObjectId("5e06ed3825ddae1f53b621ea")
]
}
Display all documents from the collection ?
db.updateOneDemo.find();
{ "_id": ObjectId("5e06ed3725ddae1f53b621e8"), "StudentId": 1, "StudentFirstName": "Chris" }
{ "_id": ObjectId("5e06ed3825ddae1f53b621e9"), "StudentId": 2, "StudentFirstName": "David" }
{ "_id": ObjectId("5e06ed3825ddae1f53b621ea"), "StudentId": 1, "StudentFirstName": "Mike" }
Example: Update Single Document
Update only the first document that matches the criteria ?
db.updateOneDemo.updateOne(
{},
{ $set: { "StudentFirstName": "Robert" } }
);
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }
Verify Result
Display all documents to see the update ?
db.updateOneDemo.find();
{ "_id": ObjectId("5e06ed3725ddae1f53b621e8"), "StudentId": 1, "StudentFirstName": "Robert" }
{ "_id": ObjectId("5e06ed3825ddae1f53b621e9"), "StudentId": 2, "StudentFirstName": "David" }
{ "_id": ObjectId("5e06ed3825ddae1f53b621ea"), "StudentId": 1, "StudentFirstName": "Mike" }
Key Points
-
updateOne()updates only the first matching document, even with an empty filter{}. - Use specific filter criteria to target the exact document you want to update.
- Returns
matchedCountandmodifiedCountin the acknowledgment.
Conclusion
The updateOne() method ensures only a single document is modified, making it ideal when you need precise control over updates. Always use specific filter criteria to target the intended document.
Advertisements
