findOneAndUpdate

更新时间:
复制 MD 格式

Finds and updates a single record.

Method definition

findOneAndUpdate(filter: object, update: object, options?: object): Promise<MongoResult>

Request parameters

Field name

Type

Required

Description

filter

Object

Yes

The query condition for the database operation.

update

Object

Yes

The replacement object for the database operation.

options

Object

No

Control options.

The options parameter contains the following fields:

Field name

Type

Required

Description

sort

Object

No

The sort order.

upsert

Boolean

No

Specifies whether to insert a document if no matching document is found. The default value is false.

projection

Object

No

Fields for filtering query results

  • 0: Does not return the field.

  • 1: Represents a return.

returnNewDocument

Boolean

No

Specifies whether to return the value of the object after it is modified.

  • true: Returns the updated document.

  • false (default): Returns the original document before the update.

maxTimeMS

Number

No

The execution time in milliseconds. The default value is 1000, and the maximum value is 3000.

Examples

  • Find the first record in the clubs collection where the score field is greater than 20000. Update its team field to "Therapeutic Hamsters" and its score field to 22250. Other fields remain unchanged.

    mpserverless.db.collection('clubs').findOneAndUpdate({ 
        score: { $gt: 20000 } 
    }, {
        $set: 
        { 
            team: "Therapeutic Hamsters", 
            score: 22250,
        }
    })
    .then(res => {})
    .catch(console.error);
  • Find the first record in the users collection where age is greater than 18, sorted by name in ascending order. Update the record's name and age fields. If no matching record is found, insert { name: "Smith", age: 22 } as a new record. The operation returns the name field and the _id field.

    mpserverless.db.collection("users").findOneAndUpdate({
        age: { $gt: 18 }
    }, {
        $set: 
        {
            name: "Smith",
            age: 22,
        }
    }, {
        projection: { name: 1 },
        sort: { name: 1 },
        upsert: true,
    })
    .then(res => {})
    .catch(console.error);