w3resource

Update every document on one field in MongoDB: Full Guide

Updating a single Field in all MongoDB Document

In MongoDB, you can update a specific field in all documents within a collection by using the updateMany() method. This approach is particularly useful when you need to apply a change across an entire dataset, such as modifying a status field or setting a default value.

Syntax:

db.collection.updateMany(
   { /* filter (optional) */ },
   { $set: { "fieldName": newValue } }
)

Explanation:

  • db.collection: Replace collection with the name of your MongoDB collection.
  • updateMany(): Updates all documents that match the filter criteria.
  • $set: MongoDB operator used to assign a new value to a field.

Example:

The following example updates the status field to "active" for every document in the users collection.

Code:

// Connect to the "users" collection and update the "status" field to "active" in all documents
db.users.updateMany(
   {}, // empty filter to target all documents
   { $set: { "status": "active" } } // set the "status" field to "active"
)

Explanation:

  • db.users.updateMany:
    • We use updateMany() on the users collection to apply an update across all documents. By passing an empty filter {}, we specify that every document should be updated.
  • { $set: { "status": "active" } }:
    • The $set operator assigns a new value to the specified field. Here, it sets "status" to "active" for each document in the collection. If a document doesn’t have the status field, this operation will add it.

Using updateMany() with an empty filter makes this method effective for updating every document in the collection with a new or modified value on a single field.

Practical Guides to MongoDB Snippets and Examples.



Follow us on Facebook and Twitter for latest update.