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
Add new field to every document in a MongoDB collection?
To add new field to every document in a MongoDB collection, you can use $set operator. The syntax is as follows ?
Syntax
db.yourCollectionName.update({}, { $set: {"yourFieldName": yourValue} }, false, true);
Sample Data
To understand the above syntax, let us create a collection with some documents. The query to create a collection with documents is as follows ?
db.addNewFieldToEveryDocument.insertMany([
{"StudentName": "John", "StudentAddress": "US"},
{"StudentName": "David", "StudentAddress": "UK"},
{"StudentName": "Carol", "StudentAddress": "UK"},
{"StudentName": "Bob", "StudentAddress": "US"}
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5c6efc0b6fd07954a48906ae"),
ObjectId("5c6efc0b6fd07954a48906af"),
ObjectId("5c6efc0b6fd07954a48906b0"),
ObjectId("5c6efc0b6fd07954a48906b1")
]
}
Display all documents from a collection with the help of find() method. The query is as follows ?
db.addNewFieldToEveryDocument.find().pretty();
The following is the output ?
{
"_id" : ObjectId("5c6efc0b6fd07954a48906ae"),
"StudentName" : "John",
"StudentAddress" : "US"
}
{
"_id" : ObjectId("5c6efc0b6fd07954a48906af"),
"StudentName" : "David",
"StudentAddress" : "UK"
}
{
"_id" : ObjectId("5c6efc0b6fd07954a48906b0"),
"StudentName" : "Carol",
"StudentAddress" : "UK"
}
{
"_id" : ObjectId("5c6efc0b6fd07954a48906b1"),
"StudentName" : "Bob",
"StudentAddress" : "US"
}
Example
The following is the query to add a new field to every document ?
db.addNewFieldToEveryDocument.update({}, { $set: {"StudentAge": 24} }, false, true);
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })
Above, we have added a new field "StudentAge":24 in every document. Let us check the field "StudentAge":24 is successfully added to every document or not. The query is as follows ?
db.addNewFieldToEveryDocument.find().pretty();
The following is the output ?
{
"_id" : ObjectId("5c6efc0b6fd07954a48906ae"),
"StudentName" : "John",
"StudentAddress" : "US",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c6efc0b6fd07954a48906af"),
"StudentName" : "David",
"StudentAddress" : "UK",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c6efc0b6fd07954a48906b0"),
"StudentName" : "Carol",
"StudentAddress" : "UK",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c6efc0b6fd07954a48906b1"),
"StudentName" : "Bob",
"StudentAddress" : "US",
"StudentAge" : 24
}
Conclusion
Use $set operator with an empty query filter {} to add a new field to every document in a MongoDB collection. The multi: true flag ensures all matching documents are updated.
