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 to add a column in MongoDB collection?
To add a column (field) in MongoDB, you need to update the collection using the $set operator. Since MongoDB is schema-less, adding a new field means updating existing documents to include the new field.
Syntax
db.collection.updateMany({}, {$set: {"newColumnName": "value"}});
Sample Data
Let us create a collection with some sample documents ?
db.addColumnDemo.insertMany([
{"StudentId": 101, "StudentName": "Chris"},
{"StudentId": 102, "StudentName": "Robert"},
{"StudentId": 103, "StudentName": "David"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e04d66af5e889d7a519950f"),
ObjectId("5e04d673f5e889d7a5199510"),
ObjectId("5e04d67bf5e889d7a5199511")
]
}
Display the current documents ?
db.addColumnDemo.find().pretty();
{
"_id": ObjectId("5e04d66af5e889d7a519950f"),
"StudentId": 101,
"StudentName": "Chris"
}
{
"_id": ObjectId("5e04d673f5e889d7a5199510"),
"StudentId": 102,
"StudentName": "Robert"
}
{
"_id": ObjectId("5e04d67bf5e889d7a5199511"),
"StudentId": 103,
"StudentName": "David"
}
Example: Adding a New Column
Add a new field StudentCityName to all documents ?
db.addColumnDemo.updateMany({}, {$set: {"StudentCityName": "New York"}});
{
"acknowledged": true,
"matchedCount": 3,
"modifiedCount": 3
}
Verify the result ?
db.addColumnDemo.find().pretty();
{
"_id": ObjectId("5e04d66af5e889d7a519950f"),
"StudentId": 101,
"StudentName": "Chris",
"StudentCityName": "New York"
}
{
"_id": ObjectId("5e04d673f5e889d7a5199510"),
"StudentId": 102,
"StudentName": "Robert",
"StudentCityName": "New York"
}
{
"_id": ObjectId("5e04d67bf5e889d7a5199511"),
"StudentId": 103,
"StudentName": "David",
"StudentCityName": "New York"
}
Key Points
- Use
updateMany()with an empty filter{}to update all documents - The
$setoperator adds new fields or updates existing ones - New fields are added instantly without affecting the collection schema
Conclusion
Adding columns in MongoDB is accomplished using updateMany() with the $set operator. This flexible approach allows you to add new fields to existing documents without schema modifications.
Advertisements
