On this page


collection.updateOne(filter, update)

Updates a single document within the collection based on the filter. The collection.updateOne() method has the following parameters.

Parameter Type Description
filter document

The selection criteria for the update. See query selectors for all available query selectors.

Specify an empty document { } to update the first document returned from the collection.

update document The modifications to apply. See Update Parameter for more information.
options document Options to apply to the update. Set to { "upsert": true } to upsert a document if no matches are found. See upsert behavior for more information.
Returns:A promise that resolves to a JSON object with the following fields:
  • matchedCount: the number of matched documents


The following examples assume that the test.example namespace has been added to MongoDB in the Stitch admin console and appropriate rules have been set. See MongoDB Rules for more information.

Updating a Document

Assume the test.example collection contains the following documents:

{ "username": "user1", "zip": "08691", "_id": ObjectId("5a0c516ac7ecd33f1aea0915") }
{ "username": "user2", "zip": "10022", "_id": ObjectId("5a0c516ac7ecd33f1aea0916") }

Assume the Stitch app contains a function named update_zip with the following definition:

exports = function(uname, new_zip) {
   const mongodb ="mongodb-atlas");
   const collection = mongodb.db("test").collection("example");

   return collection
     .updateOne({"username": uname}, {"$set": {"zip": new_zip}})
     .then(result => {
       // result.matchedCount === 1
       return result;

The function update_zip updates the document with the username matching uname and sets zip to the new_zip argument.

Clients may call this function by referring to it by name. The following example calls the function from the Javascript SDK:

stitchClient.executeFunction("update_zip", "user1", "07030")
    .then((result) => console.log(result));

This outputs:

{ "matchedCount": 1 }