CodeNewbie Community

loading...

How to bulk insert documents into a MongoDB collection

Donald Feury
Appalachian Boi
Originally published at donaldfeury.xyz on ・2 min read

Not only can you insert a single document into a collection with the insert method, it can also take in an array of documents for bulk insert operations.

The example below will insert all the documents in the given array into the collection called podcasts:

db.podcasts.insert([
    {
        "name": "Tech Over Tea",
        "episodeName": "#75 Welcome Our Hacker Neko Waifu | Cyan Nyan",
        "dateAired": ISODate("2021-08-02"),
        "odyseeURL": "https://odysee.com/@TechOverTea:3/tech-over-tea-ep75:5",
        "youtubeURL": "https://youtu.be/cc8ZTzi_fzg"
    },
    {
        "name": "Tech Over Tea",
        "episodeName": "Neckbeards Anonymous - Tech Over Tea #20 - feat Donald Feury",
        "dateAired": ISODate("2020-07-13"),
        "odyseeURL": "https://odysee.com/@TechOverTea:3/neckbeards-anonymous:5",
        "youtubeURL": "https://youtu.be/DzXLZpRS0xU"
    },
    {
        "name": "Tech Over Tea",
        "episodeName": "#34 The Return Of The Clones - feat Bryan Jenks",
        "dateAired": ISODate("2020-10-19"),
        "odyseeURL": "https://odysee.com/@TechOverTea:3/the-return-of-the-clones:a",
        "youtubeURL": "https://youtu.be/f4omYp7j05U"
    }
])

Enter fullscreen mode Exit fullscreen mode

There is also a method called insertMany that specifically only takes an array of documents as an argument, unlike insert which can operate on a single document as well as an array of documents.

More recent versions of MongoDB will give a deprecation warning when using insert and will want you to use insertMany when doing bulk inserts.

db.podcasts.insertMany([
    {
        "name": "Tech Over Tea",
        "episodeName": "#75 Welcome Our Hacker Neko Waifu | Cyan Nyan",
        "dateAired": ISODate("2021-08-02"),
        "odyseeURL": "https://odysee.com/@TechOverTea:3/tech-over-tea-ep75:5",
        "youtubeURL": "https://youtu.be/cc8ZTzi_fzg"
    },
    {
        "name": "Tech Over Tea",
        "episodeName": "Neckbeards Anonymous - Tech Over Tea #20 - feat Donald Feury",
        "dateAired": ISODate("2020-07-13"),
        "odyseeURL": "https://odysee.com/@TechOverTea:3/neckbeards-anonymous:5",
        "youtubeURL": "https://youtu.be/DzXLZpRS0xU"
    },
    {
        "name": "Tech Over Tea",
        "episodeName": "#34 The Return Of The Clones - feat Bryan Jenks",
        "dateAired": ISODate("2020-10-19"),
        "odyseeURL": "https://odysee.com/@TechOverTea:3/the-return-of-the-clones:a",
        "youtubeURL": "https://youtu.be/f4omYp7j05U"
    }
])

Enter fullscreen mode Exit fullscreen mode

Discussion (0)