Finds and updates a single record.
Method definition
findOneAndUpdate(filter: object, update: 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 options. |
The options parameter contains the following fields:
Field name | Type | Required | Description |
|---|---|---|---|
| Object | No | The sort order. |
| Boolean | No | Specifies whether to insert a document if no matching document is found. The default value is |
| Object | No | Fields for filtering query results
|
| Boolean | No | Specifies whether to return the value of the object after it is modified.
|
| 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
clubscollection where thescorefield is greater than 20000. Update itsteamfield to "Therapeutic Hamsters" and itsscorefield 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
ageis greater than 18, sorted bynamein ascending order. Update the record'snameandagefields. If no matching record is found, insert{ name: "Smith", age: 22 }as a new record. The operation returns thenamefield and the_idfield.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);