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 do I add a field to existing record in MongoDB?
You can use the update command with the $set operator to add a field to existing records in MongoDB. This operation can add fields to specific documents or to all documents in a collection.
Syntax
db.collection.update(
{ query },
{ $set: { "newFieldName": value } },
{ multi: true }
);
Sample Data
db.addAFieldToEveryRecordDemo.insertMany([
{ "ClientName": "Chris", "ClientAge": 34 },
{ "ClientName": "Robert", "ClientAge": 36 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd00e32588d4a6447b2e061"),
ObjectId("5cd00e59588d4a6447b2e062")
]
}
Display Current Documents
db.addAFieldToEveryRecordDemo.find().pretty();
{
"_id": ObjectId("5cd00e32588d4a6447b2e061"),
"ClientName": "Chris",
"ClientAge": 34
}
{
"_id": ObjectId("5cd00e59588d4a6447b2e062"),
"ClientName": "Robert",
"ClientAge": 36
}
Example: Add Field to All Records
Add a nested field "ClientDetails.ClientCountryName" to all documents ?
db.addAFieldToEveryRecordDemo.update(
{},
{ $set: { "ClientDetails.ClientCountryName": "" } },
{ multi: true }
);
WriteResult({ "nMatched": 2, "nUpserted": 0, "nModified": 2 })
Verify Results
db.addAFieldToEveryRecordDemo.find().pretty();
{
"_id": ObjectId("5cd00e32588d4a6447b2e061"),
"ClientName": "Chris",
"ClientAge": 34,
"ClientDetails": {
"ClientCountryName": ""
}
}
{
"_id": ObjectId("5cd00e59588d4a6447b2e062"),
"ClientName": "Robert",
"ClientAge": 36,
"ClientDetails": {
"ClientCountryName": ""
}
}
Key Points
- Empty query
{}matches all documents in the collection. -
{ multi: true }ensures the update applies to all matching documents. - Dot notation creates nested fields automatically if they don't exist.
Conclusion
Use $set with an empty query and multi: true to add fields to all existing records. The operation creates nested structures automatically when using dot notation.
Advertisements
