🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to MongoDB Notes
Topic #8

MongoDB Update


Update Document

To update an existing document we can use the updateOne() or updateMany() methods.

The first parameter is a query object to define which document or documents should be updated.

The second parameter is an object defining the updated data.


updateOne()

The updateOne() method will update the first document that is found matching the provided query.

Let's see what the "like" count for the post with the title of "Post Title 1":

Example

db.posts.find( { title: "Post Title 1" } )

Now let's update the "likes" on this post to 2. To do this, we need to use the $set operator.

Example

db.posts.updateOne( { title: "Post Title 1" }, { $set: { likes: 2 } } )

Check the document again and you'll see that the "like" have been updated.

Example

db.posts.find( { title: "Post Title 1" } )

Insert if not found

If you would like to insert the document if it is not found, you can use the upsert option.

Example

db.posts.updateOne(
  { title: "Post Title 5" },
  {
    $set:
      {
        title: "Post Title 5",
        body: "Body of post.",
        category: "Event",
        likes: 5,
        tags: ["news", "events"],
        date: Date()
      }
  },
  { upsert: true }
)

updateMany()

The updateMany() method will update all documents that match the provided query.

Example

db.posts.updateMany({}, { $inc: { likes: 1 } })

Now check the likes in all of the documents and you will see that they have all been incremented by 1.

Want to go beyond the notes?

Join CodingNow 2.0's MongoDB course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

MongoDB Update – FAQs

Quick answers about learning MongoDB Update in MongoDB.

This free note from CodingNow 2.0 explains MongoDB Update in MongoDB — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every MongoDB topic on CodingNow 2.0, including MongoDB Update, is 100% free with no signup required.
With focused practice, most students grasp MongoDB Update in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now