Navigation

collection.updateOne()

Definition

collection.updateOne()

Update a single document in a collection based on a query filter.

Usage

Example

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

const query = { "name": "football" };
const update = {
  "$push": {
    "reviews": {
      "username": "tombradyfan",
      "comment": "I love football!!!"
    }
  }
};
const options = { "upsert": false };

itemsCollection.updateOne(query, update, options)
  .then(result => {
    const { matchedCount, modifiedCount } = result;
    if(matchedCount && modifiedCount) {
      console.log(`Successfully added a new review.`)
    }
  })
  .catch(err => console.error(`Failed to add review: ${err}`))

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

const query = { "name": "football" };
const update = {
  "$push": {
    "reviews": {
      "username": "tombradyfan",
      "comment": "I love football!!!"
    }
  }
};
const options = { "upsert": false };

itemsCollection.updateOne(query, update, options)
  .then(result => {
    const { matchedCount, modifiedCount } = result;
    if(matchedCount && modifiedCount) {
      console.log(`Successfully added a new review.`)
    }
  })
  .catch(err => console.error(`Failed to add review: ${err}`))

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

Document filterDoc = new Document().append("name", "football");
Document updateDoc = new Document().append("$push",
    new Document().append("reviews", new Document()
        .append("username", "stitchfan2018")
        .append("comment", "what a neat product")
    )
);

final Task <RemoteUpdateResult> updateTask =
  itemsCollection.updateOne(filterDoc, updateDoc);
updateTask.addOnCompleteListener(new OnCompleteListener <RemoteUpdateResult> () {
    @Override
    public void onComplete(@NonNull Task <RemoteUpdateResult> task) {
        if (task.isSuccessful()) {
            long numMatched = task.getResult().getMatchedCount();
            long numModified = task.getResult().getModifiedCount();
            Log.d("app", String.format("successfully matched %d and modified %d documents",
                  numMatched, numModified));
        } else {
            Log.e("app", "failed to update document with: ", task.getException());
        }
    }
});

To call the collection.updateOne() action from the Swift/iOS SDK, use the RemoteMongoCollection.updateOne() method.

let query : Document = ["name": "football"];
let update : Document = [
    "$push": [
        "reviews": [
            "username": "stitchfan2018",
            "comment": "what a neat product"
        ] as Document
    ] as Document
];

itemsCollection?.updateOne(filter: query, update: update) { result in
    switch result {
    case .success(let result):
        if result.matchedCount && result.modifiedCount {
            print("Successfully added a new review.")
        } else {
            print("Could not find a matching item.")
        }
    case .failure(let error):
        print("Failed to update: \(error)");
    }
}

Parameters

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

updateOne(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>
}

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.

The updateOne() method has the following form:

updateOne(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>
}

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.

The updateOne() method has the following form:

updateOne(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>
}

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.

The updateOne() method has the following form:

updateOne(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>
}

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.

Return Value

The collection.updateOne() action returns a Promise that resolves to a document that describes the update operation.

Promise<result: document>

The RemoteMongoCollection.updateOne() method returns a Promise that resolves to a RemoteUpdateResult object that describes the update operation.

Promise<result: RemoteUpdateResult>

The RemoteMongoCollection.updateOne() method returns a Task that resolves to a RemoteUpdateResult object that describes the update operation.

Task<RemoteUpdateResult result>

The RemoteMongoCollection.updateOne() method returns a StitchResult enum that resolves to a RemoteUpdateResult object that describes the update operation.

enum StitchResult {
  case success(result: RemoteUpdateResult)
  case failure(error: StitchError)
}
Value Description

Matched Count

result.matchedCount: <integer>
result.matchedCount: <integer>
result.matchedCount: <Long>
result.matchedCount: <Int>
The number of documents in the collection that match the provided query filter.

Modified Count

result.modifiedCount: <integer>
result.modifiedCount: <integer>
result.modifiedCount: <Long>
result.modifiedCount: <Int>
The number of documents in the collection that were modified by the update operation.

Upserted ID

result.upsertedId: <ObjectID>
result.upsertedId: <ObjectID>
result.upsertedId: <ObjectID>
result.upsertedId: <ObjectID>
The _id value of the document inserted by an upsert operation. This value is only present when the upsert option is enabled and the update query does not match any documents.