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
Updating a MongoDB document and adding new keys only in the first document?
To update a MongoDB document and add new keys only to the first document in a collection, use the update() method with an empty query filter and $set operator. This targets the first document that matches the query criteria.
Syntax
db.collection.update(
{},
{ $set: { "newField": "value" } },
{ upsert: true }
);
Sample Data
db.demo162.insertMany([
{ "StudentName": "Chris" },
{ "StudentName": "Bob" },
{ "StudentName": "David" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3684359e4f06af551997c2"),
ObjectId("5e3684389e4f06af551997c3"),
ObjectId("5e36843c9e4f06af551997c4")
]
}
Example: Add New Field to First Document
Add a StudentAge field with value 23 to the first document ?
db.demo162.update(
{},
{ $set: { "StudentAge": 23 } },
{ upsert: true }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.demo162.find();
{ "_id": ObjectId("5e3684359e4f06af551997c2"), "StudentName": "Chris", "StudentAge": 23 }
{ "_id": ObjectId("5e3684389e4f06af551997c3"), "StudentName": "Bob" }
{ "_id": ObjectId("5e36843c9e4f06af551997c4"), "StudentName": "David" }
How It Works
- Empty query filter
{}matches all documents butupdate()only modifies the first match by default -
$setoperator adds the new field or updates existing field values -
upsert: truecreates a new document if no matches are found (optional)
Conclusion
Use update() with an empty query filter and $set to add new fields only to the first document. MongoDB's default behavior updates just the first matching document unless multi: true is specified.
Advertisements
