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 document containing:
  • matchedCount containing the number of matched documents

Examples

The following examples assume that the test.example namespace has been added to the MongoDB service and appropriate rules have been set. See MongoDB Service 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() {
    var mongodb = context.services.get("mongodb-atlas");
    var coll = mongodb.db("test").collection("example");
    return coll.updateMany({}, {"$inc": {"grade": 9}});
};

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") }