- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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" }
- Related Articles
- Add new field to every document in a MongoDB collection?
- Display only a single field from all the documents in a MongoDB collection
- Find all duplicate documents in a MongoDB collection by a key field?
- How to delete all the documents from a collection in MongoDB?
- How to insert new documents into a MongoDB collection in your database?
- How to retrieve all the documents from a MongoDB collection using Java?
- How to sum the value of a key across all documents in a MongoDB collection?
- How to remove all documents from a collection except a single document in MongoDB?
- MongoDB query to update each field of documents in collection with a formula?
- How to delete documents from a collection in MongoDB?
- How to retrieve documents from a collection in MongoDB?
- MongoDB query to add up the values of a specific field in documents
- How to create a new collection in MongoDB?
- Finding documents in MongoDB collection where a field is equal to given integer value?
- How to count the number of documents in a MongoDB collection?

Advertisements