On this page



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 the MongoDB service and appropriate rules have been set. See MongoDB Service Rules for more information.

Counting all Documents in a Collection

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

Returning 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) {
    var mongodb ="mongodb-atlas");
    var coll = mongodb.db("test").collection("example");
    return coll.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