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?

7/10/2018 12:20:33 AM

Accepted Answer

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

Check out this example:

{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item =
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
>{"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }


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

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


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

                          {$set : {"new_field":1}},
7/10/2018 12:27:02 AM

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)

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)

From documents

update_many(filter, update, upsert=False, array_filters=None, bypass_document_validation=False, collation=None, session=None)

filter: A query that matches the documents to update.

update: The modifications to apply.

upsert (optional): If True, perform an insert if no documents match the filter.

bypass_document_validation (optional): If True, allows the write to opt-out of document level validation. Default is False.

collation (optional): An instance of Collation. This option is only supported on MongoDB 3.4 and above.

array_filters (optional): A list of filters specifying which array elements an update should apply. Requires MongoDB 3.6+.

session (optional): a ClientSession.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]