count

更新时间:
复制 MD 格式

Retrieves the number of records in a collection that match the filter condition. This operation scans all documents in the collection. A query timeout may occur if the collection contains many documents.

Method definition

count(query: object, options?: object): Promise<MongoResult>

Request parameters

Field name

Type

Required

Description

query

Object

Yes

The filter condition.

options

Object

No

Controls.

The options parameter contains the following fields:

Field name

Type

Required

Description

limit

Number

No

The maximum number of documents to count.

skip

Number

No

The number of documents to skip before the count operation begins.

maxTimeMS

Number

No

The running time in milliseconds. Default: 1000. Maximum: 3000.

Request examples

  • Count the number of records in the users collection.

mpserverless.db.collection('users').count({
    age: { $gt: 18 }
}).then((res) => {
    console.log(res);
}).catch(console.error);
  • Count the records in the users collection where age is 18 or greater.

mpserverless.db.collection('users').count({
    age: { $gt: 18 }
}).then((res) => {
    console.log(res);
}).catch(console.error);
  • Count the number of records in the myNoteBook collection where the value of the title field is 1 and the value of the userId field is 2088112127936xxx. Then, print the result.

mpserverless.db.collection('myNoteBook').count({ 
    title: "1", 
    userId: "2088112127936xxx", 
}).then((res) => {
    console.log(res);
}).catch(console.error);

Result examples

  • Successful request

{
    "affectedDocs": 2,
    "result": 2,
    "success": true
}
  • Failed request

{
    "success": false,
    "error": {
        "code": "InternalServerError",
        "message": "Error in $cursor stage :: caused by :: operation exceeded time limit"
    }
}