DEV Community

Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

1 1

How to update a single document in a MongoDB collection

For a full overview of MongoDB and all my posts on it, check out my overview.

You can update existing documents in MongoDB and if you want to update only one document at a time you have three main options.

You can use the update method to update one document. By default, it will only update one document, even if the query provided matches multiple documents.

First, we'll insert our data set into a collection called podcasts using insertMany

db.podcasts.insertMany([
    {
        "name": "Tech Over Tea",
        "episodeName": "#75 Welcome Our Hacker Neko Waifu | Cyan Nyan",
        "dateAired": ISODate("2021-08-02"),
        "listenedTo": true,
    },
    {
        "name": "Tech Over Tea",
        "episodeName": "Neckbeards Anonymous - Tech Over Tea #20 - feat Donald Feury",
        "dateAired": ISODate("2020-07-13"),
        "listenedTo": true
    },
    {
        "name": "Tech Over Tea",
        "episodeName": "#34 The Return Of The Clones - feat Bryan Jenks",
        "dateAired": ISODate("2020-10-19"),
        "listenedTo": false
    }
])

Enter fullscreen mode Exit fullscreen mode

Let's update the podcast episode that aired on 2020-10-19 to indicate we've listened to it now.

db.podcasts.update({dateAired: ISODate("2020-10-19")}, {
    { $set: { listenedTo: true } }
})

Enter fullscreen mode Exit fullscreen mode

The first argument is our query specifies what document we want to update. The second argument is a document describing how we want to update the document.

We're using what is called a update operator called set to tell MongoDB to update the listenedTo to the new value of true.

We can achieve the same result with updateOne.

db.podcasts.updateOne({dateAired: ISODate("2020-10-19")}, {
    { $set: { listenedTo: true } }
})

Enter fullscreen mode Exit fullscreen mode

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay