MongoDB Create Document (CRUD) Tutorial

In this MongoDB tutorial we learn the first CRUD operation, creating documents.

We cover how to create single documents as well as how to create multiple documents at once.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

How to create (insert) new documents

If we want to create new documents and add them to a collection, we use the db.collection.insert() method.

This method takes one argument.

  • document to specify the data to be inserted

The terminal/command prompt will allow you to write the data on separate lines by pressing Enter after each line. Once the function’s parameter list is closed with the closing bracket, pressing Enter will run the command.

    "title":        "How to Mongo",
    "description":  "Learn how to Mongo",
    "author":       "John Doe",
    "url":          "/how-to-mongo/",
    "tags":         ["MongoDB", "Database", "Learn"],
    "likes":        10,
    "rating":       [{ "score": 6 }, { "score": 7 }],
        "user":     "Jane",
        "comment":  "Thanks for the toot",
        "likes":    4
        "user":     "Jack",
        "comment":  "You forgot DB at the end",
        "likes":    3

If the operation succeeded, the terminal will return with an affirmative message indicating how many documents were created.

WriteResult({ "nInserted" : 1 })

Alternatively, we can use the db.collection.insertOne() function in the exact same way if we only need to create a single document in a collection.

How to create multiple new documents at once

We can create multiple new documents at once by passing an array as argument for the db.collection.insert() method.

        "name": "John",
        "email": ""
        "name": "Jane",
        "email": ""

The terminal will return the statistics of the operation.

    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 2,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]

In this case both users were added to the document so the nInserted field shows 2.

Alternatively, we can use the db.collection.insertMany() function in the exact same way.