Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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:
db.yourCollectionName.update({}, { $set: {"yourFieldName": yourValue} }, false, true);
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.insertOne({"StudentName":"John","StudentAddress":"US
"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6efc0b6fd07954a48906ae")
}
>db.addNewFieldToEveryDocument.insertOne({"StudentName":"David","StudentAddress":"U
K"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6efc0b6fd07954a48906af")
}
>db.addNewFieldToEveryDocument.insertOne({"StudentName":"Carol","StudentAddress":"U
K"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6efc0b6fd07954a48906b0")
}
>db.addNewFieldToEveryDocument.insertOne({"StudentName":"Bob","StudentAddress":"US"
});
{
"acknowledged" : true,
"insertedId" : 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"
}
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
}Advertisements