Navigation

collection.count()

Definition

collection.count()

Return the number of documents in a collection or view that match the specified query filter.

Usage

Example

To call the collection.count() action from a Function, get a collection handle with database.collection() then call the handle’s count() method.

collection.count({ status: "Complete" })
  .then(numDocs => console.log(`${numDocs} documents match the specified query.`))
  .catch(err => console.error("Failed to count documents: ", err))

To call the collection.count() action from a JavaScript SDK, use the RemoteMongoCollection.count() method.

collection.count({ status: "Complete" })
  .then(numDocs => console.log(`${numDocs} documents match the specified query.`))
  .catch(err => console.error("Failed to count documents: ", err))

To call the collection.count() action from the Java/Android SDK, use the RemoteMongoCollection.count() method.

collection.count(new Document("status", "Complete"))
  .addOnCompleteListener(new OnCompleteListener <Long> () {
    @Override
    public void onComplete(@NonNull Task <Long> task) {
      if (task.isSuccessful()) {
        Long numDocs = task.getResult();
        Log.d("app", String.format(
          "%s documents match the specified query.",
          numDocs.toString()
        ));
      } else {
        Log.e("app", "Failed to count documents with exception: ", task.getException());
      }
    }
  });

To call the collection.count() action from the Swift/iOS SDK, use the RemoteMongoCollection.count() method.

collection.count(["status", "Complete"]) { result in
  switch result {
  case .success(let numDocs):
    print("\(numDocs) documents match the specified query.")
  case .failure(let error):
    print("Failed to count documents: ", error)
  }
}

Parameters

The collection.count() action has the following form:

count(query)
Parameter Description

Query Filter

query: <document>

Optional. A standard MongoDB query document that specifies which documents to count. You can use most query selectors except for evaluation, geospatial, or bitwise selectors.

Specify an empty query filter ({}) or omit this parameter to count all documents in the collection.

The count() method has the following form:

count(query)
Parameter Description

Query Filter

query: <document>

Optional. A standard MongoDB query document that specifies which documents to count. You can use most query selectors except for evaluation, geospatial, or bitwise selectors.

Specify an empty query filter ({}) or omit this parameter to count all documents in the collection.

The count() method has the following form:

count(query)
Parameter Description

Query Filter

query: <document>

Optional. A standard MongoDB query document that specifies which documents to count. You can use most query selectors except for evaluation, geospatial, or bitwise selectors.

Specify an empty query filter ({}) or omit this parameter to count all documents in the collection.

The count() method has the following form:

count(query)
Parameter Description

Query Filter

query: <document>

Optional. A standard MongoDB query document that specifies which documents to count. You can use most query selectors except for evaluation, geospatial, or bitwise selectors.

Specify an empty query filter ({}) or omit this parameter to count all documents in the collection.

Return Value

The collection.count() action returns a Promise that resolves to the integer number of documents in the collection that match the query filter.

Promise<numDocs: Number>

The RemoteMongoCollection.count() method returns a Promise that resolves to the integer number of documents in the collection that match the query filter.

Promise<numDocs: Number>

The RemoteMongoCollection.count() method returns a Task that resolves to the integer number of documents in the collection that match the query filter.

Task<Long numDocs>

The RemoteMongoCollection.count() method returns a StitchResult enum that resolves to the integer number of documents in the collection that match the query filter.

enum StitchResult {
  case success(numDocs: Int)
  case failure(error: StitchError)
}
Value Description

Count Result

numDocs: <integer>
numDocs: <integer>
numDocs: <Long>
numDocs: <Int>
The number of documents in the collection that match the provided query filter.

Examples

The following examples assume that you have defined roles and permissions that allow the database operations on the test.example collection.

Counting All Documents in a Collection

exports = function() {
    const mongodb = context.services.get("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 = context.services.get("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 = context.services.get("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