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
How to add a new field to all the documents in a MongoDB collection
To add a new field, use $addFields in MongoDB. Let us create a collection with documents −
> db.demo712.insertOne({"Name":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea85f675d33e20ed1097b82")
}
> db.demo712.insertOne({"Name":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea85f6a5d33e20ed1097b83")
}
> db.demo712.insertOne({"Name":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea85f6e5d33e20ed1097b84")
}
Display all documents from a collection with the help of find() method −
> db.demo712.find();
This will produce the following output −
{ "_id" : ObjectId("5ea85f675d33e20ed1097b82"), "Name" : "John" }
{ "_id" : ObjectId("5ea85f6a5d33e20ed1097b83"), "Name" : "Chris" }
{ "_id" : ObjectId("5ea85f6e5d33e20ed1097b84"), "Name" : "Bob" }
Following is the query to add a new field −
> db.demo712.aggregate([
... {
... $addFields:
... {
... "TeacherName":"Robert"
... }
... }
... ]
... );
This will produce the following output −
{ "_id" : ObjectId("5ea85f675d33e20ed1097b82"), "Name" : "John", "TeacherName" : "Robert" }
{ "_id" : ObjectId("5ea85f6a5d33e20ed1097b83"), "Name" : "Chris", "TeacherName" : "Robert" }
{ "_id" : ObjectId("5ea85f6e5d33e20ed1097b84"), "Name" : "Bob", "TeacherName" : "Robert" }Advertisements