Navigation

collection.deleteMany()

On this page

Definition

collection.deleteMany(filter)

Removes a documents from the collection based on the filter. The collection.deleteMany() method has the following parameters.

Parameter Type Description
filter document

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

Specify an empty document { } to remove the first document returned from the collection.

Returns:A document containing:
  • deletedCount containing the number of deleted 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.

Deleting Multiple Documents

Assume the test.example collection contains the following documents:

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

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

exports = function(start, end) {
    var mongodb = context.services.get("mongodb-atlas");
    var coll = mongodb.db("test").collection("example");
    return coll.deleteMany({"grade": {"$gt": start, "$lt": end}});
};

The function delete_grades deletes documents with the grades between start and end.

Clients may call this function by referring to it by name. The following example calls the function from the Javascript SDK:

stitchClient.executeFunction("delete_grades", 80, 100)
    .then((result) => console.log(result));

This outputs:

{ "deletedCount": 3 }