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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more