MongoDB updateOne

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

In this article we will review the updateOne function in MongoDB. We will start by reviewing its function definition and then showing demonstration using JavaScript. we will talk about exactly what the function and went to apply.

Prerequisites

  • You should have MongoDB installed on your system.

What updateOne Does?

The updateOne() function updates the first document in a collection that matches the specified filter.

It’s a simple function but can come in handy especially when you intend to only update a single document. This function will insure that at the most one document is changed. This is a good insurance policy in case you make a mistake on the filter. If you run a normal update command and make a mistake on the filter you could update more documents than you intend.

The updateOne function definition

Let’s start by reviewing the updateOne function definition for the Mongo Shell:

1
db.collection.updateOne(filter, update, [options])

Note: Although this syntax is for the mongo shell, the syntax for your driver should be very similar whether you are using JavaScript, PHP, or Python. At the end of this tutorial we will show an example using the JavaScript driver.

As you can see, the function takes in three parameters: filter, update, and options.

  • ( Document ) The filter parameter is used to specify the document that you want to update. If you leave filter as an empty object then the update will take place on the first object returned from the collection.
  • ( Document ) The update parameter specifies the modifications that you want to make to the document. Some operators commonly use here are $set end $unset.
  • ( Document ) The options parameter is optional. There are a range of options available and you should see the documentation if you’d like to use them. In this demonstration we are showing updateOne’s most common usage.

What does it return? The function returns a document containing the following: acknowledged – True or false depending on whether the update was successful matchedCount – The number of documents that matched the filter. modifiedCount – The number of documents that were updated. upsertedId – If a document was upserted then this is the _id of that document.

Example using the Mongo Shell

Assume we have a database grocerydb with a collection products that contains this data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
        "_id" : ObjectId("5d12c9974b74efae4662b8df"),
        "name" : "Soda",
        "quantity" : 10,
        "price" : 5.5
}
{
        "_id" : ObjectId("5d12c9a34b74efae4662b8e0"),
        "name" : "Bread",
        "quantity" : 9,
        "price" : 2.5
}
{
        "_id" : ObjectId("5d12c9b24b74efae4662b8e1"),
        "name" : "Milk",
        "quantity" : 4,
        "price" : 3
}

To update the price of the Milk to $3.50 we could use the updateOne() command as follows:

1
db.products.updateOne({name:"Milk"}, {$set:{price:3.5}})

And we receive the following response:

1
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Now we can validate the update by viewing the Milk document with the following command:

1
db.products.find({name:"Milk"})

As you can see from the response below the price was updated as expected:

1
2
3
4
5
6
{
        "_id" : ObjectId("5d12c9b24b74efae4662b8e1"),
        "name" : "Milk",
        "quantity" : 4,
        "price" : 3.5
}

A Javascript Example

If you’re running MongoDB using Javascript with NodeJS with the official drivers, you’re script will look something like below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("grocerydb");
  var filter = { name: "Milk" };
  var update = { $set: {price: 3.5} };
  dbo.collection("products").updateOne(filter, update, function(err, res) {
    if (err) throw err;
    console.log("Successfully updated the price of Milk");
    db.close();
  });
});

Conclusion

In this article we demonstrated how to use the updateOne function in the MongoDB shell and in JavaScript. We described the function definition and when it might be a good idea to use this function. We hope this article helped you use this function correctly. If you need someone you can trust to manage your MongoDB database please don’t hesitate to reach out to us at Object Rocket.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.