CodeNewbie Community

Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

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

Discussion (0)