DEV Community

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

Posted on • Originally published at donaldfeury.xyz on

2 1

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.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

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

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay