add new field in mongo collection documents

How to add new field in an existing Mongo DB collection document

This sneppet teaches you how to add new field to every existing document in the mongo db collection. You have to use db.collection.update() with $set operator to perform this operation in the same way you used to update existing field in the collection documents.

Add new field to existing mongo documents

If you want to add new field to all your collection documents, then you have to use empty selector, set upsert flag to false and multi flag to true in the mongo update method to update all the documents

db.collection.update(
  {},
  { $set: {"new_field": <value>} },
  false,
  true
)

Example

For example, let’s say you wanted to add new filed called “site_name” in all the documents in the following collection “items” ,

> use sneppets
switched to db sneppets

> db.items.find()
{ "_id" : ObjectId("5ca86a71d9caf05c4d9af01e"), "id" : 1, "item_name" : "Lenova
E4430", "qty" : 2, "price" : 98000 }
{ "_id" : ObjectId("5ca86a71d9caf05c4d9af01f"), "id" : 2, "item_name" : "Mac Pro
 Desktop", "qty" : 1, "price" : 95456 }
{ "_id" : ObjectId("5ca86a71d9caf05c4d9af020"), "id" : 3, "item_name" : "Microso
ft LAM-00001 Surface Studio 2", "qty" : 1, "price" : 910000 }
>

Run the following mongo command and check whether new field is added as required. Note, you should get WriteResult result status as shown below.

> db.items.update(
... {},
... { $set:{"site_name":"https://www.amazon.in"} },
... false,
... true
... )
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

You can verify whether new field is added or not either through command db.items.find() method or through MongoDB compass community.

add new field in mongo collection documents

Further Learning

References

Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Eric
Eric
3 years ago

thanks