Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (47.6k points)
edited by

How can I add a new field to every document in an existent collection?

I know how to update an existing document's field but not how to add a new field to every document in a collection. How can I do this in the mongo shell?

1 Answer

0 votes
by (106k points)

To add a new field to every document in a MongoDB collection you have to use empty selector, and set the multi flag to true to update all the documents as follows:-

db.your_collection.update( 

  {}, 

  { $set: {"new_field": 1} }, 

  false, 

  true 

)

Related questions

0 votes
2 answers
asked Sep 13, 2019 in SQL by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...