findOneAndReplace

更新时间:
复制 MD 格式

Replaces a single document and returns the original document before the replacement.

Method definition

findOneAndReplace(filter: object, replacement: object, options?: object): Promise<MongoResult>

Request parameters

Field Name

Type

Required

Description

filter

Object

Yes

The query condition for the database operation.

replacement

Object

Yes

The replacement object for the database operation.

options

Object

No

Control.

The options parameter includes 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 match is found. The default value is false.

projection

Object

No

The fields to return from the query.

maxTimeMS

Number

No

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

Examples

  • Find the first document in the clubs collection where the score field is greater than 20000, and replace it with { team: "Therapeutic Hamsters", score: 22250}.

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

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