findOne

更新时间:
复制 MD 格式

Finds a single record.

Method definition

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

Request parameters

Field name

Type

Required

Description

query

Object

No

The query conditions for the database operation.

options

Object

No

Control options.

The options parameter contains the following fields:

Field name

Type

Required

Description

skip

Number

No

The number of documents to skip.

sort

Object

No

Specifies the field for sorting and the sort order. Use 1 or -1.

  • 1: Ascending order.

  • -1: Descending order.

projection

Object

No

Specifies the fields to return using projection operators. Fields set to 1 are returned. Fields set to 0 are hidden.

hint

Object

No

Specifies the index to use for the query.

maxTimeMS

Number

No

The running time in milliseconds. The default value is 1000. The maximum value is 3000.

Examples

  • Find a record in the users collection where the age field is greater than 18. The query sorts the results by the name field in ascending order, skips 10 records, and returns the name field of the first match. The _id field is also returned by default. The query uses the name field as the index instead of _id.

    mpserverless.db.collection('users').findOne({
        age: { $gt: 18 }
    }, {
        projection: { name: 1 },
        sort: { name: 1 },
        skip: 10,
        hint: { name: 1 }
    })
    .then(res => {})
    .catch(console.error);
  • Find a record in the users collection. The query sorts the records by the name field in ascending order, skips 10 records, and returns the name field of the first match. The _id field is also returned by default. The query uses the name field as the index instead of _id.

    mpserverless.db.collection('users').findOne({}, {
        projection: { name: 1 },
        sort: { name: 1 },
        skip: 10,
        hint: { name: 1 }
    })
    .then(res => {})
    .catch(console.error);