

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 do I add a field to existing record in MongoDB?
You can use update command to add a field to existing record. Let us first create a collection with documents −
> db.addAFieldToEveryRecordDemo.insertOne({"ClientName":"Chris","ClientAge":34}); { "acknowledged" : true, "insertedId" : ObjectId("5cd00e32588d4a6447b2e061") } > db.addAFieldToEveryRecordDemo.insertOne({"ClientName":"Robert","ClientAge":36}); { "acknowledged" : true, "insertedId" : ObjectId("5cd00e59588d4a6447b2e062") }
Following is the query to display all documents from a collection with the help of find() method −
> db.addAFieldToEveryRecordDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd00e32588d4a6447b2e061"), "ClientName" : "Chris", "ClientAge" : 34 } { "_id" : ObjectId("5cd00e59588d4a6447b2e062"), "ClientName" : "Robert", "ClientAge" : 36 }
Here is the query to add a field to every record. We are adding ClientDetails −
>db.addAFieldToEveryRecordDemo.update({},{$set:{"ClientDetails.ClientCountryName":""}},true,true); WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
Let us check all documents have been added with new record or not −
> db.addAFieldToEveryRecordDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd00e32588d4a6447b2e061"), "ClientName" : "Chris", "ClientAge" : 34, "ClientDetails" : { "ClientCountryName" : "" } } { "_id" : ObjectId("5cd00e59588d4a6447b2e062"), "ClientName" : "Robert", "ClientAge" : 36, "ClientDetails" : { "ClientCountryName" : "" } }
- Related Questions & Answers
- How do I push elements to an existing array in MongoDB?
- How to add a field with specific datatype (list, object) in an existing MongoDB document?
- Remove and update the existing record in MongoDB?
- How do I check whether a field contains null value in MongoDB?
- How to update record in MongoDB without replacing the existing fields?
- How do I exclude a specific record in MySQL?
- How can I add a Boolean field to MySQL?
- How to update field to add value to existing value in MySQL?
- How do I add a value to the top of an array in MongoDB?
- How do I order a list and add position to its items in MongoDB?
- How to search for a record (field) and then delete it in MongoDB?
- How do I find all documents with a field that is NaN in MongoDB?
- How do I query a MongoDB collection?
- How to add an extra field in a sub document in MongoDB?
- Add new field to every document in a MongoDB collection?
Advertisements