Navigation

collection.updateMany()

On this page

Definition

collection.updateMany(filter, update)

Updates multiple documents within the collection based on the filter. The collection.updateMany() method has the following parameters.

Parameter Type Description
filter document

The selection criteria for the update. See query selectors for all available query selectors.

Specify an empty document { } to update the all documents in the collection.

update document The modifications to apply. See Update Parameter for more information.
Returns:A promise that resolves to a JSON object with the following fields:
  • matchedCount: the number of matched documents

Examples

The following examples assume that the test.example namespace has been added to MongoDB in the Stitch admin console and appropriate rules have been set. See MongoDB Rules for more information.

Updating Multiple Documents

Assume the test.example collection contains the following documents:

{ "grade": 91, "_id": ObjectId("5a0c516ac7ecd33f1aea091A") }
{ "grade": 89, "_id": ObjectId("5a0c516ac7ecd33f1aea0916") }
{ "grade": 87, "_id": ObjectId("5a0c516ac7ecd33f1aea0915") }
{ "grade": 68, "_id": ObjectId("5a0c516ac7ecd33f1aea0919") }
{ "grade": 62, "_id": ObjectId("5a0c516ac7ecd33f1aea0917") }
{ "grade": 22, "_id": ObjectId("5a0c516ac7ecd33f1aea0918") }

MongoDB Stitch contains a function named apply_curve with the following definition:

exports = function() {
   const mongodb = context.services.get("mongodb-atlas");
   const collection = mongodb.db("test").collection("example");
   collection
     .updateMany({}, {"$inc": {"grade": 9}})
     .then(result => {
       // result.matchedCount === number of records that were updated
       return result;
     });
};

Calling apply_curve returns the following document:

{ "matchedCount": 6 }

The resulting documents in test.example are as follows:

{ "grade": 100, "_id": ObjectId("5a0c516ac7ecd33f1aea091A") }
{ "grade": 98, "_id": ObjectId("5a0c516ac7ecd33f1aea0916") }
{ "grade": 96, "_id": ObjectId("5a0c516ac7ecd33f1aea0915") }
{ "grade": 77, "_id": ObjectId("5a0c516ac7ecd33f1aea0919") }
{ "grade": 71, "_id": ObjectId("5a0c516ac7ecd33f1aea0917") }
{ "grade": 31, "_id": ObjectId("5a0c516ac7ecd33f1aea0918") }