Sling Academy
Home/MongoDB/MongoDB db.collection.updateOne() method (with examples)

MongoDB db.collection.updateOne() method (with examples)

Last updated: February 03, 2024

Overview

In MongoDB, updating documents is a common task, and understanding how to effectively use the updateOne method is crucial for database management and manipulation. This tutorial will guide you through the db.collection.updateOne() method, including its syntax, parameters, and multiple practical examples to cover a variety of use cases.

The Basics of db.collection.updateOne()

The db.collection.updateOne() method is a powerful function in MongoDB that allows you to update the first document that matches the query criteria. It’s an essential tool for developers and DBAs looking to modify a single document within a collection.

Syntax

db.collection.updateOne(
  <filter>,
  <update>,
  {
    upsert: <boolean>,
    collation: <document>,
    arrayFilters: [<filterdocument>],
    hint: <document | string>
  }
)

Parameters

  • filter: A document specifying the criteria used to select the document to update.
  • update: The modifications to apply to the selected document. Can be either:
    • A document that specifies the field(s) to be updated and the values to use, or
    • An update operator like $set, which specifies the fields to modify and their new values.
  • upsert (optional): If set to true, a new document is created if no documents match the update query.
  • collation (optional): Specifies the collation to use for string comparison. Useful for specifying languages and strengths for comparison.
  • arrayFilters (optional): Specifies which array elements to modify for an update operation within an array field.
  • hint (optional): If provided, specifies the index to use when performing the operation.

Basic Example

Let’s start with a simple example to update a document in a collection named users. Assume we want to update a user named ‘John Doe’ to change his email:

db.users.updateOne(
  { "name": "John Doe" },
  { $set: { "email": "[email protected]" } }
);

Advanced Scenarios

Updating Nested Fields

To update a document that contains nested fields, you use the dot notation. For example, to update the city of a user:

db.users.updateOne(
  { "name": "John Doe" },
  { $set: { "address.city": "New York" } }
);

Upsert Option

When you’re unsure if the document exists, you can use the upsert option to create a new document if it does not exist:

db.users.updateOne(
  { "name": "Jane Doe" },
  { $set: { "email": "[email protected]" } },
  { upsert: true }
);

Using ArrayFilters

Array filters can be extremely useful when you need to update specific elements within an array. For example, to update only the scores that are less than 50 in a user’s profile:

db.users.updateOne(
  { "name": "John Doe" },
  { $set: { "scores.$[elem]": 60 } },
  { arrayFilters: [{ "elem": { $lt: 50 } }] }
);

Hint Option

Using hint can optimize the performance of your update query by forcing MongoDB to use a specific index:

db.users.updateOne(
  { "name": "John Doe" },
  { $set: { "email": "[email protected]" } },
  { hint: 'name_index' }
);

Best Practices

  • Always use the $set operator to update specific fields in a document to avoid accidentally overwriting the entire document.
  • Consider using upsert for operations where the presence of the document is uncertain.
  • Utilize collation for accurate string comparisons in international applications.
  • Employ arrayFilters for targeted updates in array fields.
  • When performance is critical, use hint to direct MongoDB to use an efficient index.

Conclusion

The db.collection.updateOne() method is a versatile tool in your MongoDB arsenal. With its array of options and operators, you can precisely modify a single document according to complex criteria and conditions. Remembering the tips and examples provided in this guide will help you utilize this method effectively for a variety of update operations on your collections. Happy coding!

Next Article: MongoDB db.collection.updateMany() method (with examples)

Previous Article: MongoDB: Insert multiple documents and get their IDs (with examples)

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)