[mongodb] 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?

This question is related to mongodb field nosql

The answer is


Since MongoDB version 3.2 you can use updateMany():

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

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.

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)

if you are using mongoose try this,after mongoose connection

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

Examples related to mongodb

Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Failed to start mongod.service: Unit mongod.service not found db.collection is not a function when using MongoClient v3.0 MongoError: connect ECONNREFUSED 127.0.0.1:27017 MongoDB: How To Delete All Records Of A Collection in MongoDB Shell? How to resolve Nodejs: Error: ENOENT: no such file or directory How to create a DB for MongoDB container on start up?

Examples related to field

String field value length in mongoDB Javascript - removing undefined fields from an object Set field value with reflection How to add additional fields to form before submit? jquery how to empty input field Add new field to every document in a MongoDB collection How to remove leading and trailing whitespace in a MySQL field? jQuery - Detect value change on hidden input field disable all form elements inside div SSRS Field Expression to change the background color of the Cell

Examples related to nosql

Firestore Getting documents id from collection What is Hash and Range Primary Key? Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061 Explanation of JSONB introduced by PostgreSQL DynamoDB vs MongoDB NoSQL Querying DynamoDB by date Delete all nodes and relationships in neo4j 1.8 When to use CouchDB over MongoDB and vice versa Difference between scaling horizontally and vertically for databases NoSQL Use Case Scenarios or WHEN to use NoSQL