CodeNewbie Community 🌱

Cover image for How to replace an existing document in MongoDB
Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

How to replace an existing document in MongoDB

How to replace an existing document in MongoDB


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

MongoDB provides several ways to update specifically one document that works great when doing partial updates.

If you want to completely replace an existing document with a new one, you can use replaceOne.

First, let's insert some data into a collection called podcasts:

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 completely replace the podcast that aired on 2020-07-13 with a new podcast. Unlike update and updateOne, replaceOne does not use update operators.

db.podcasts.replaceOne(
    {dateAired: ISODate("2020-07-13")},
    {
        "name": "Tech Over Tea",
        "episodeName": "#73 Is This A Gaming Podcast Now | Solo",
        "dateAired": ISODate("2021-07-19"),
        "listenedTo": false
    }
)

Enter fullscreen mode Exit fullscreen mode

The arguments are similar to update and updateOne where the first argument is the query to match a document to replace. However, the second argument is a new document that will completely replace the first matched document.

Top comments (0)