Navigation

collection.findOneAndUpdate()

Definition

collection.findOneAndUpdate()

Update a single document in a collection or view based on a query filter and return the document in either its pre-update or post-update form. Unlike collection.updateOne(), this action allows you to atomically find, update, and return a document with the same command. This avoids the risk of other update operations changing the document between separate find and update operations.

Usage

Example

To call the collection.findOneAndUpdate() action from a Function, get a collection handle with database.collection() then call the handle’s findOneAndUpdate() method.

// Find the document that describes "legos"
const query = { "name": "legos" };
// Set some fields in that document
const update = {
  "$set": {
    "name": "blocks",
    "price": 20.99,
    "category": "toys"
  }
};
// Return the updated document instead of the original document
const options = { returnNewDocument: true };

return itemsCollection.findOneAndUpdate(query, update, options)
  .then(updatedDocument => {
    if(updatedDocument) {
      console.log(`Successfully updated document: ${updatedDocument}.`)
    } else {
      console.log("No document matches the provided query.")
    }
    return updatedDocument
  })
  .catch(err => console.error(`Failed to find and update document: ${err}`))

To call the collection.findOneAndUpdate() action from a JavaScript SDK, use the RemoteMongoCollection.findOneAndUpdate() method.

// Find the document that describes "legos"
const query = { "name": "legos" };
// Set some fields in that document
const update = {
  "$set": {
    "name": "blocks",
    "price": 20.99,
    "category": "toys"
  }
};
// Return the updated document instead of the original document
const options = { returnNewDocument: true };

itemsCollection.findOneAndUpdate(query, update, options)
  .then(updatedDocument => {
    if(updatedDocument) {
      console.log(`Successfully updated document: ${updatedDocument}.`)
    } else {
      console.log("No document matches the provided query.")
    }
    return updatedDocument
  })
  .catch(err => console.error(`Failed to find and update document: ${err}`))

To call the collection.findOneAndUpdate() action from the Java/Android SDK, use the RemoteMongoCollection.findOneAndUpdate() method.

// Find the document that describes "legos"
Document query = new Document().append("name", "legos");

// Set some fields in that document
Document update = new Document().append("$set", new Document()
    .append("name", "blocks")
    .append("price", Decimal128.parse("20.99"))
    .append("category", "toys"));

Document projection = new Document()
    .append("_id", 1)
    .append("name", 1)
    .append("price", 1);
Document sort = new Document()
    .append("name", 1);

RemoteFindOneAndModifyOptions options = new RemoteFindOneAndModifyOptions()
    // Return the updated document instead of the original document
    .returnNewDocument(true)
    .upsert(false)
    .sort(sort)
    .projection(projection);

final Task <Document> findOneAndUpdateTask = itemsCollection.findOneAndUpdate(query, update, options);
findOneAndUpdateTask.addOnCompleteListener(new OnCompleteListener <Document> () {
    @Override
    public void onComplete(@NonNull Task <Document> task) {
        if (task.getResult() == null) {
            Log.d("app", String.format("No document matches the provided query"));
        }
        else if (task.isSuccessful()) {
            Log.d("app", String.format("Successfully updated document: %s",
                    task.getResult()));
        } else {
            Log.e("app", "Failed to findOneAndUpdate: ", task.getException());
        }
    }
});
let query: Document = ["name": "legos"]
// MongoDB recommends monetary data be stored as Decimal128
let update: Document = ["$set": [
    "name": "blocks",
    "price": Decimal128("20.99"),
    "category": "toys",
] as Document]
// return the document in its updated form
let options = RemoteFindOneAndModifyOptions.init(returnNewDocument: true)
itemsCollection?.findOneAndUpdate(filter: query, update: update, options: options) { result in
    switch result {
    case .success(let doc):
        switch doc {
        case .none:
            print("No document matches the provided query")
        case .some(let doc):
            print("Successfully updated document: \(doc)")
        }
    case .failure(let err):
        print("Failed to findOneAndUpdate: \(err)")
    }
}

Parameters

The collection.findOneAndUpdate() action has the following form:

findOneAndUpdate(query, update, options)
Parameter Description

Query Filter

query: <document>

Required. A standard MongoDB query document that specifies which document to update. You can use most query selectors except for evaluation, geospatial, or bitwise selectors.

If multiple documents match the query, only the first document in sort order or natural order will be updated.

Update Operation

update: <document>
Required. A standard MongoDB update document that specifies the update operation to perform on the document that matches the query. You can use most update operators.

Update Options

options: <document>

A document that specifies configuration options for the query. The options document has the following form:

{
   "upsert": <boolean>,
   "sort": <document>,
   "projection": <document>,
   "returnNewDocument": <boolean>
}

Upsert

options.upsert: <boolean>
Optional. Default: false. A boolean that, if true, indicates that MongoDB should insert a new document that matches the query filter when the query does not match any existing documents in the collection.

Sort

options.sort: <document>

Optional. Specifies the query sort order. Sort documents specify one or more fields to sort on where the value of each field indicates whether MongoDB should sort it in ascending (1) or descending (-1) order. The sort order determines which document collection.findOneAndUpdate() affects.

Example

The following sort document specifies that documents should be sorted first by age from highest to lowest. Once sorted by age, the result set should further be sorted by name in alphabetical order for each distinct age value.

{ age: -1, name: 1 }

Projection

options.projection: <document>

Optional. A document that specifies which fields MongoDB should return or withhold in each document that matches the query.

To return all fields in the matching documents, omit this parameter or specify an empty projection document ({}).

To return specific fields and the document’s _id, specify the fields in the projection document with a value of 1:

// Includes the field in returned documents
{ <Field Name>: 1 }

To withhold specific fields, specify the fields in the projection document with a value of 0:

// Withholds the field from returned documents
{ <Field Name>: 0 }

Note

You may specify either fields to include or fields to withhold but not both. For example, the following projection is invalid because it simultaneously includes the name field and withholds the address field:

// Invalid
// Can't simultaneously include and withhold
{ "name": 1, "address": 0 }

The exception to this rule is the _id field, which you may withhold from any query:

// Valid
// Can exclude _id while including other fields
{ "_id": 0, "name": 1 }

Return New Document

options.returnNewDocument: <boolean>
Optional. Default: false. A boolean that, if true, indicates that the action should return the document in its updated form instead of its original, pre-update form.

The findOneAndUpdate() method has the following form:

findOneAndUpdate(query, update, options)
Parameter Description

Query Filter

query: <document>

Required. A standard MongoDB query document that specifies which document to update. You can use most query selectors except for evaluation, geospatial, or bitwise selectors.

If multiple documents match the query, only the first document in sort order or natural order will be updated.

Update Operation

update: <document>
Required. A standard MongoDB update document that specifies the update operation to perform on the document that matches the query. You can use most update operators.

Update Options

options: <document>

A document that specifies configuration options for the query. The options document has the following form:

{
   "upsert": <boolean>,
   "sort": <document>,
   "projection": <document>,
   "returnNewDocument": <boolean>
}

Upsert

options.upsert: <boolean>
Optional. Default: false. A boolean that, if true, indicates that MongoDB should insert a new document that matches the query filter when the query does not match any existing documents in the collection.

Sort

options.sort: <document>

Optional. Specifies the query sort order. Sort documents specify one or more fields to sort on where the value of each field indicates whether MongoDB should sort it in ascending (1) or descending (-1) order. The sort order determines which document collection.findOneAndUpdate() affects.

Example

The following sort document specifies that documents should be sorted first by age from highest to lowest. Once sorted by age, the result set should further be sorted by name in alphabetical order for each distinct age value.

{ age: -1, name: 1 }

Projection

options.projection: <document>

Optional. A document that specifies which fields MongoDB should return or withhold in each document that matches the query.

To return all fields in the matching documents, omit this parameter or specify an empty projection document ({}).

To return specific fields and the document’s _id, specify the fields in the projection document with a value of 1:

// Includes the field in returned documents
{ <Field Name>: 1 }

To withhold specific fields, specify the fields in the projection document with a value of 0:

// Withholds the field from returned documents
{ <Field Name>: 0 }

Note

You may specify either fields to include or fields to withhold but not both. For example, the following projection is invalid because it simultaneously includes the name field and withholds the address field:

// Invalid
// Can't simultaneously include and withhold
{ "name": 1, "address": 0 }

The exception to this rule is the _id field, which you may withhold from any query:

// Valid
// Can exclude _id while including other fields
{ "_id": 0, "name": 1 }

Return New Document

options.returnNewDocument: <boolean>
Optional. Default: false. A boolean that, if true, indicates that the action should return the document in its updated form instead of its original, pre-update form.

The findOneAndUpdate() method has the following form:

findOneAndUpdate​(Bson filter, Bson update, RemoteFindOneAndModifyOptions options, Class<ResultT> resultClass)
Parameter Description

Query Filter

filter: <document>

Required. A standard MongoDB query document that specifies which document to update. You can use most query selectors except for evaluation, geospatial, or bitwise selectors.

If multiple documents match the query, only the first document in sort order or natural order will be updated.

Update Operation

update: <document>
Required. A standard MongoDB update document that specifies the update operation to perform on the document that matches the query. You can use most update operators.

Update Options

options: <RemoteFindOneAndModifyOptions>

Optional: An instance of the RemoteFindOneAndModifyOptions. class.

RemoteFindOneAndModifyOptions options =
  new RemoteFindOneAndModifyOptions()
  .sort(<document>)
  .projection(<document>)
  .returnNewDocument(<bool>)
  .upsert(<bool>);

Sort

RemoteFindOneAndModifyOptions.sort: <document>

Optional. Specifies the query sort order. Sort documents specify one or more fields to sort on where the value of each field indicates whether MongoDB should sort it in ascending (1) or descending (-1) order. The sort order determines which document collection.findOneAndUpdate() affects.

Example

The following sort document specifies that documents should be sorted first by age from highest to lowest. Once sorted by age, the result set should further be sorted by name in alphabetical order for each distinct age value.

Document sort = new Document()
 .append("age", -1)
 .append("name", 1);

Projection

RemoteFindOneAndModifyOptions.projection: <document>

Optional. A document that specifies which fields MongoDB should return or withhold in the document returned by the query.

To return all fields in the matching document, omit this parameter or specify an empty projection document (new Document()).

To return specific fields and the document’s _id, specify the fields in the projection document with a value of 1:

// Includes the field in returned document
Document sort = new Document()
  .append(<Field Name>, 1);

To withhold specific fields, specify the fields in the projection document with a value of 0:

// Withholds the field from returned document
Document sort = new Document()
  .append(<Field Name>, 0);

Note

You may specify either fields to include or fields to withhold but not both. For example, the following projection is invalid because it simultaneously includes the name field and withholds the address field:

// Invalid
// Can't simultaneously include and withhold
Document sort = new Document()
 .append("name", 1)
 .append("address", 0);

The exception to this rule is the _id field, which you may withhold from any query:

// Valid
// Can exclude _id while including other fields
Document sort = new Document()
 .append("_id", 0)
 .append("name", 1);

Upsert

RemoteFindAndModifyOptions.upsert: <boolean>
Optional. Default: false. A boolean that, if true, indicates that MongoDB should insert a new document that matches the query filter when the query does not match any existing documents in the collection.

Return New Document

RemoteFindAndModifyOptions.returnNewDocument: <boolean>
Optional. Default: false. A boolean that, if true, indicates that the action should return the document in its post-replace form instead of its original form from before the replace operation.

Result Class

resultClass: <class>
Optional. Indicates the type of the document returned by the operation.
public func findOneAndUpdate(filter: Document,
                 update: Document,
                 options: RemoteFindOneAndModifyOptions? = nil,
                 _ completionHandler: @escaping (StitchResult<CollectionType?>) -> Void)
Parameter Description

Query Filter

filter: <document>

Required. A standard MongoDB query document that specifies which document to update. You can use most query selectors except for evaluation, geospatial, or bitwise selectors.

If multiple documents match the query, only the first document in sort order or natural order will be updated.

Update Operation

update: <document>
Required. A standard MongoDB update document that specifies the update operation to perform on the document that matches the query. You can use most update operators.

Update Options

options: <RemoteFindOneAndModifyOptions>

Optional: A RemoteFindOneAndModifyOptions> struct that can be initialized with the following values.

RemoteFindOneAndModifyOptions.init(
    "sort": <document>,
    "projection": <document>,
    "upsert": <bool>,
    "returnNewDocument": <bool>
)

Sort

RemoteFindOneAndModifyOptions.sort: <document>

Optional. Specifies the query sort order. Sort documents specify one or more fields to sort on where the value of each field indicates whether MongoDB should sort it in ascending (1) or descending (-1) order. The sort order determines which document collection.findOneAndUpdate() affects.

Example

The following sort document specifies that documents should be sorted first by age from highest to lowest. Once sorted by age, the result set should further be sorted by name in alphabetical order for each distinct age value.

[ "age": -1, "name": 1 ]

Projection

RemoteFindOneAndModifyOptions.projection: <document>

Optional. A document that specifies which fields MongoDB should return or withhold in each document that matches the query.

To return all fields in the matching documents, omit this parameter or specify an empty projection document ([]).

To return specific fields and the document’s _id, specify the fields in the projection document with a value of 1:

// Includes the field in returned documents
[ <Field Name>: 1 ]

To withhold specific fields, specify the fields in the projection document with a value of 0:

// Withholds the field from returned documents
[ <Field Name>: 0 ]

Note

You may specify either fields to include or fields to withhold but not both. For example, the following projection is invalid because it simultaneously includes the name field and withholds the address field:

// Invalid
// Can't simultaneously include and withhold
[ "name": 1, "address": 0 ]

The exception to this rule is the _id field, which you may withhold from any query:

// Valid
// Can exclude _id while including other fields
[ "_id": 0, "name": 1 ]

Upsert

RemoteFindAndModifyOptions.upsert: <boolean>
Optional. Default: false. A boolean that, if true, indicates that MongoDB should insert a new document that matches the query filter when the query does not match any existing documents in the collection.

Return New Document

RemoteFindAndModifyOptions.returnNewDocument: <boolean>
Optional. Default: false. A boolean that, if true, indicates that the action should return the document in its post-replace form instead of its original form from before the replace operation.

completionHandler

(StitchResult<CollectionType?>) -> Void

Required. A completion handler that accepts StitchResult optional.

This should be matched to check for successful completion of the operation.

Return Value

Note

You can specify whether to return the pre-replacement or post-replacement version of the document by setting the value of options.returnNewDocument. By default, returnNewDocument is false, which indicates that the promise should resolve to the pre-update version of the document.

The collection.findOneAndUpdate() action returns a Promise that resolves to a single document that the query overwrote. If no documents match the specified query, the promise resolves to null.

Promise<document|null>

Note

You can specify whether to return the pre-replacement or post-replacement version of the document by setting the value of options.returnNewDocument. By default, returnNewDocument is false, which indicates that the promise should resolve to the pre-update version of the document.

The collection.findOneAndUpdate() action returns a Promise that resolves to a single document that the query overwrote. If no documents match the specified query, the promise resolves to null.

Promise<document|null>

Note

You can specify whether to return the pre-replacement or post-replacement version of the document by setting the value of RemoteFindAndModifyOptions.returnNewDocument. By default, returnNewDocument is false, which indicates that onComplete should be called with a Task containing the pre-update version of the document.

The findOneAndUpdate() function returns a Task containing the returned document, which can be accessed using the task.getResult() method. The type of the result contained within the Task varies based on the configuration of the RemoteMongoCollection used for the operation and the value of the resultClass parameter.

  • If resultClass is specified, the returned Task contains an object of type ResultT, which resolves to type resultClass.
  • If a resultClass is not specified, the returned Task contains an object of type DocumentT, which resolves to type Document unless otherwise specified when the RemoteMongoCollection was instantiated.
  • If no document matches the provided query and the upsert option is false, task.getResult() will return null.
  • If the operation fails for any other reason, the task will fail and details can be accessed using task.getException(). If no
Task<ResultT result | DocumentT result | null>

Note

You can specify whether to return the pre-replacement or post-replacement version of the document by setting the value of RemoteFindAndModifyOptions.returnNewDocument. By default, returnNewDocument is false, which indicates that completionHandler should be called with a StitchResult containing the pre-update version of the document.

The findOneAndUpdate method will call the supplied completionHandler with a StitchResult.