How to replace an existing document in MongoDB

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.

How to replace an existing document in MongoDB
Image made by BoneCloset

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
    }
])

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
	}
)

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.


Did you find this information useful? If so, consider heading over to my donation page and drop me some support.

Want to ask a question or just chat? Contact me here