Updating a Single Document in MongoDB: The updateOne() Method

Learn how to effectively modify a single document in MongoDB collections using the updateOne() method. This guide will cover the various update operators and techniques, allowing you to precisely target and modify the desired document. Understand the behavior of updateOne() when multiple documents match the filter criteria.



MongoDB: Update Single Document using updateOne()

The updateOne() method in MongoDB updates a single document that matches the specified filter criteria. It modifies the first matching document even if multiple documents match.

Syntax

The syntax for the updateOne() method is:

Syntax

db.collection.updateOne(filter, update, options)
        

Parameters:

  • filter: The selection criteria for the update, similar to the find() method.
  • update: A document or pipeline that contains modifications to apply.
  • options: Optional. May include options for update behavior like upsert, writeConcern, collation, etc.

Sample Data

Insert the following documents into the employees collection:

Insert Sample Data

db.employees.insertMany([
    { _id: 1, firstName: "John", lastName: "King", email: "john.king@abc.com", salary: 5000 },
    { _id: 2, firstName: "Sachin", lastName: "T", email: "sachin.t@abc.com", salary: 8000 },
    { _id: 3, firstName: "James", lastName: "Bond", email: "jamesb@abc.com", salary: 7500 },
    { _id: 4, firstName: "Steve", lastName: "J", email: "steve.j@abc.com", salary: 7000 },
    { _id: 5, firstName: "Kapil", lastName: "D", email: "kapil.d@abc.com", salary: 4500 },
    { _id: 6, firstName: "Amitabh", lastName: "B", email: "amitabh.b@abc.com", salary: 7000 }
])
        

Examples

1. **Update a Single Field**

Update the firstName field of the document with _id: 1:

Example: Update a Single Field

db.employees.updateOne({_id: 1}, { $set: { firstName: 'Morgan' } })
        

Output:

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
    

Check the updated document:

Check Updated Document

db.employees.find({_id: 1})
        

Output:

{
  _id: 1,
  firstName: 'Morgan',
  lastName: 'King',
  email: 'john.king@abc.com',
  salary: 5000
}
    

2. **Add a New Field**

Add the location field to the document with firstName: "Steve":

Example: Add a New Field

db.employees.updateOne({firstName: "Steve"}, { $set: { location: "USA" } })
        

Output:

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
    

Check the updated document:

Check Updated Document

db.employees.find({firstName: "Steve"})
        

Output:

{
  _id: 4,
  firstName: "Steve",
  lastName: "J",
  email: "steve.j@abc.com",
  salary: 7000,
  location: "USA"
}
    

3. **Use the $inc Operator**

Increase the salary field by 500 for the document with firstName: "Steve":

Example: Use the $inc Operator

db.employees.updateOne({firstName: "Steve"}, { $inc: { salary: 500 } })
        

Output:

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
    

Check the updated document:

Check Updated Document

db.employees.find({firstName: "Steve"})
        

Output:

{
  _id: 4,
  firstName: "Steve",
  lastName: "J",
  email: "steve.j@abc.com",
  salary: 7500,
  location: "USA"
}
    

4. **Update Multiple Fields**

Update the email and lastName fields for the document with _id: 2:

Example: Update Multiple Fields

db.employees.updateOne({_id: 2}, { $set: { lastName: "Tendulkar", email: "sachin.tendulkar@abc.com" } })
        

Output:

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
    

Check the updated document:

Check Updated Document

db.employees.find({_id: 2})
        

Output:

{
  _id: 2,
  firstName: "Sachin",
  lastName: "Tendulkar",
  email: "sachin.tendulkar@abc.com",
  salary: 8000
}
    

5. **Upsert - Add if Not Exist**

Add a new document if no document matches the filter:

Example: Upsert

db.employees.updateOne({firstName: "Heer"}, { $set: { lastName: "Patel", salary: 2000 } }, { upsert: true })
        

Output:

{
  acknowledged: true,
  insertedId: ObjectId("6172a2e9ce7d5ca09d6ab082"),
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 1
}
    

Update Operators

Here are some common update operators you can use with updateOne():

Method Description
$currentDate Sets the value of a field to the current date, either as a Date or a Timestamp.
$inc Increments the value of the field by the specified amount.
$min Only updates the field if the specified value is less than the existing field value.
$max Only updates the field if the specified value is greater than the existing field value.
$mul Multiplies the value of the field by the specified amount.
$rename Renames a field.
$set Sets the value of a field in a document.
$setOnInsert Sets the value of a field if an update results in an insert of a document. Has no effect on updates that modify existing documents.
$unset Removes the specified field from a document.

For more details, refer to the MongoDB Update Operators documentation.