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 |
|---|---|---|---|
| Object | Yes | The query condition for the database operation. |
| Object | Yes | The replacement object for the database operation. |
| Object | No | Control. |
The options parameter includes the following fields:
Field name | Type | Required | Description |
|---|---|---|---|
| Object | No | The sort order. |
| Boolean | No | Specifies whether to insert a document if no match is found. The default value is |
| Object | No | The fields to return from the query. |
| 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
clubscollection where thescorefield 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
userscollection where theagefield is greater than 18, sorted by name in ascending order, and replace it with{name: "Smith", age: 22}. The operation returns thenameand_idfields 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);