Selects documents in a collection or view and returns the number of selected documents.

Parameter Type Description
query document

Optional. Specifies a selection filter using query selectors.

Specify an empty document { } or omit this parameter to return the count of all documents in the collection.

Returns:An integer representing the number of matched documents.


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.

Counting All Documents in a Collection

exports = function() {
    const mongodb ="mongodb-atlas");
    const collection = mongodb.db("test").collection("example");
    return collection.count();

Counting Documents Matching a Regular Expression

Regular expressions must be encoded to BSON.

exports = function() {
  const mongodb ="mongodb-atlas");
  const coll = mongodb.db("test").collection("example");

  const regex = BSON.BSONRegExp("com\.domain\..+", "i")
  return coll.count({ "package": { "$regex": regex } }).toArray();

Counting the Number of Documents Matching User Input

Assume the test.example collection contains the following documents:

{ "username": "user1", comment: "abc", "_id": ObjectId("5a0c516ac7ecd33f1aea0915") }
{ "username": "user1", comment: "def", "_id": ObjectId("5a0c516ac7ecd33f1aea0916") }
{ "username": "user2", comment: "ghi", "_id": ObjectId("5a0c516ac7ecd33f1aea0917") }

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

exports = function(uname) {
    const mongodb ="mongodb-atlas");
    const collection = mongodb.db("test").collection("example");
    return collection.count({"username": uname});

The function count_comments returns the number of documents with the username matching the argument.

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

stitchClient.executeFunction("count_comments", "user1")
    .then((num_returned) => {
        console.log("Found " + num_returned + " documents");

This outputs:

Found 2 documents