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
I want to create a new field in an already created document. How can this be done using MongoDB query?
To create a new field in an already existing MongoDB document, use the $set operator with the update() method. The $set operator adds new fields or modifies existing field values.
Syntax
db.collection.update(
{ "matchingField": "value" },
{ $set: { "newFieldName": "newValue" } }
);
Create Sample Data
Let us first create a collection with documents ?
db.createFieldDemo.insertMany([
{ "StudentFirstName": "John", "StudentAge": 21 },
{ "StudentFirstName": "Larry", "StudentAge": 23 },
{ "StudentFirstName": "Chris", "StudentAge": 22 },
{ "StudentFirstName": "David", "StudentAge": 25 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd99e28b50a6c6dd317ad95"),
ObjectId("5cd99e2fb50a6c6dd317ad96"),
ObjectId("5cd99e38b50a6c6dd317ad97"),
ObjectId("5cd99e43b50a6c6dd317ad98")
]
}
Display all documents to verify the data ?
db.createFieldDemo.find().pretty();
{
"_id": ObjectId("5cd99e28b50a6c6dd317ad95"),
"StudentFirstName": "John",
"StudentAge": 21
}
{
"_id": ObjectId("5cd99e2fb50a6c6dd317ad96"),
"StudentFirstName": "Larry",
"StudentAge": 23
}
{
"_id": ObjectId("5cd99e38b50a6c6dd317ad97"),
"StudentFirstName": "Chris",
"StudentAge": 22
}
{
"_id": ObjectId("5cd99e43b50a6c6dd317ad98"),
"StudentFirstName": "David",
"StudentAge": 25
}
Example: Adding a New Field
Create a new field "StudentLastName" for David's document ?
db.createFieldDemo.update(
{ _id: ObjectId("5cd99e43b50a6c6dd317ad98") },
{ $set: { "StudentLastName": "Miller" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Check all documents to see the newly added field ?
db.createFieldDemo.find().pretty();
{
"_id": ObjectId("5cd99e28b50a6c6dd317ad95"),
"StudentFirstName": "John",
"StudentAge": 21
}
{
"_id": ObjectId("5cd99e2fb50a6c6dd317ad96"),
"StudentFirstName": "Larry",
"StudentAge": 23
}
{
"_id": ObjectId("5cd99e38b50a6c6dd317ad97"),
"StudentFirstName": "Chris",
"StudentAge": 22
}
{
"_id": ObjectId("5cd99e43b50a6c6dd317ad98"),
"StudentFirstName": "David",
"StudentAge": 25,
"StudentLastName": "Miller"
}
Key Points
-
$setcreates new fields as simple values, unlike$addToSetwhich creates arrays - Use
updateMany()to add the same field to multiple documents - If the field already exists,
$setwill update its value
Conclusion
Use the $set operator with update() to create new fields in existing MongoDB documents. This approach adds clean field-value pairs without creating unnecessary array structures.
Advertisements
