462

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?

ndmeiri
  • 4,979
  • 12
  • 37
  • 45
itsme
  • 48,972
  • 96
  • 224
  • 345

7 Answers7

748

Same as the updating existing collection field, $set will add a new fields if the specified field does not exist.

Check out this example:

> db.foo.find()
> db.foo.insert({"test":"a"})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item = db.foo.findOne()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }

EDIT:

In case you want to add a new_field to all your collection, you have to use empty selector, and set multi flag to true (last param) to update all the documents

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

EDIT:

In the above example last 2 fields false, true specifies the upsert and multi flags.

Upsert: If set to true, creates a new document when no document matches the query criteria.

Multi: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.

This is for Mongo versions prior to 2.2. For latest versions the query is changed a bit

db.your_collection.update({},
                          {$set : {"new_field":1}},
                          {upsert:false,
                          multi:true}) 
ndmeiri
  • 4,979
  • 12
  • 37
  • 45
RameshVel
  • 64,778
  • 30
  • 169
  • 213
76

Since MongoDB version 3.2 you can use updateMany():

> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})
qwertz
  • 1,894
  • 17
  • 13
  • 2
    I think `updateMany` is more readable – francis Apr 01 '22 at 19:37
  • How can I implement it to an array of objects? like ```some_arr[{_id:1},{_id:2},{_id:1}]```. I want to add a new field status to each object in the array in all MongoDB documents in a collection – ARHAM RUMI Mar 01 '23 at 10:41
25

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)
LineDrop
  • 461
  • 4
  • 5
18
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.

Sai Krishna
  • 597
  • 4
  • 16
jatinS
  • 566
  • 6
  • 6
  • 2
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Suraj Rao Sep 27 '21 at 06:25
5

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)
Ghasem
  • 14,455
  • 21
  • 138
  • 171
  • Is it "update_many" or "updateMany" ? – Abdulhakim Oct 01 '21 at 18:46
  • @Abdulhakim it's [`update_many`](https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.update_many) – Ghasem Oct 04 '21 at 07:52
  • Hey guys, can I add a new field to each document from an array which is having a different value for each document. – JAbr Mar 02 '22 at 14:44
  • @JAbr I don't know the answer, but better open a new question, because unless they're follow-ups to the original question, people don't usually answer new questions in the comments. – RobertSF Mar 24 '22 at 18:51
  • 1
    @AlexJolig for Mongodb shell, it's [`updateMany`](https://www.mongodb.com/docs/v4.4/reference/method/db.collection.updateMany/#mongodb-method-db.collection.updateMany) – Bersan Oct 22 '22 at 16:37
2

if you are using mongoose try this,after mongoose connection

async ()=> await Mongoose.model("collectionName").updateMany({}, {$set: {newField: value}})
Edgar Olivar
  • 1,348
  • 13
  • 13
  • hey @Edgar can you explain this in more detail by taking an example, and can you share documents , where you have found this? – Rohan Devaki Dec 05 '20 at 03:34
  • hi @RohanDevaki , yes, https://mongoosejs.com/docs/models.html in "Updating" sections, in that page you see the example: "Tank" model = Mongoose.model("Tank") and the updateMany function you can find in https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/ – Edgar Olivar Dec 07 '20 at 11:43
  • but while setting a new filed, you also need to mention the type of the new field right, where did you mention the type, and you have to add, whether it is required or not, how will you add these? – Rohan Devaki Dec 07 '20 at 13:21
2

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.

KushalSeth
  • 3,265
  • 1
  • 26
  • 29