'Add new field to every document in a MongoDB collection

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?



Solution 1:[1]

Since MongoDB version 3.2 you can use updateMany():

> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})

Solution 2:[2]

To clarify, the syntax is as follows for MongoDB version 4.0.x:

db.collection.update({},{$set: {"new_field*":1}},false,true)

Here is a working example adding a published field to the articles collection and setting the field's value to true:

db.articles.update({},{$set: {"published":true}},false,true)

Solution 3:[3]

Pymongo 3.9+

update() is now deprecated and you should use replace_one(), update_one(), or update_many() instead.

In my case I used update_many() and it solved my issue:

db.your_collection.update_many({}, {"$set": {"new_field": "value"}}, upsert=False, array_filters=None)

Solution 4:[4]

db.collection.updateMany({}, {$set: {"fieldName": ""}})

updateMany requires a matching condition for each document, since we are passing {} it is always true. And the second argument uses $set operator to add the required field in each document.

Solution 5:[5]

if you are using mongoose try this,after mongoose connection

async ()=> await Mongoose.model("collectionName").updateMany({}, {$set: {newField: value}})

Solution 6:[6]

The answers above does't cover this scenario. I was looking for the similar query but want to add fields to few documents based on condition.

So, we can use first variable of updateMany to update fields only in few documents.

Example: I want to add a nullable field isDeprecated? to all those Users whose userType is Employer and has country "AAA".

db.users.updateMany({"userType": "Employer", "country": "AAA"}, {"$set": { "isDeprecated?": true }})  

This answer will be helpful in those scenarios as well, where we have to find the collection and then update. This can we done in single query like mentioned.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 qwertz
Solution 2 LineDrop
Solution 3
Solution 4 KRRISH96
Solution 5 Edgar Olivar
Solution 6