MongoDB Insert Document

In this post, we will learn how to insert single and multiple documents in MongoDB collection.

Insert a Single Document

db.collection.insertOne() inserts a single document into a collection.
The following example inserts a new document into the posts collection. If the document does not specify an _id field, MongoDB adds the _id field with an ObjectId value to the new document.
> db.posts.insertOne({
    title: 'MongoDB Overview',
    description: 'MongoDB is no sql database',
    by: 'Java Guides',
    url: 'https://www.javaguides.net',
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 500
 });
{
        "acknowledged" : true,
        "insertedId" : ObjectId("5e1823977695f4d696a05984")
}
insertOne() returns a document that includes the newly inserted document’s _id field value.
Here "posts" is our collection name. If the collection doesn't exist in the database, then MongoDB will create this collection and then insert a document into it.
To retrieve the document that you just inserted, query the collection:
> db.posts.find().pretty();
{
        "_id" : ObjectId("5e198ead41b7a7bd66f65982"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database",
        "by" : "Java Guides",
        "url" : "https://www.javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 500
}
The below diagram shows the summary of all the commands used to insert a single document:

Insert Multiple Documents

db.collection.insertMany() can insert multiple documents into a collection. Pass an array of documents to the method.
The following example inserts two new documents into the posts collection. If the documents do not specify an _id field, MongoDB adds the _id field with an ObjectId value to each document.
db.posts.insertMany([
   {
      title: 'MongoDB Overview', 
      description: 'MongoDB is no sql database',
      by: 'Java Guides',
      url: 'https://javaguides.net',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 100
   },
 
   {
      title: 'NoSQL Database', 
      description: "NoSQL database doesn't have tables",
       by: 'Java Guides',
      url: 'https://javaguides.net',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 20, 
      comments: [ 
         {
            user:'user1',
            message: 'My first comment',
            dateCreated: new Date(2013,11,10,2,35),
            like: 0 
         }
      ]
   }
]);

{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5e18246f7695f4d696a05985"),
                ObjectId("5e18246f7695f4d696a05986")
        ]
}
insertMany() returns a document that includes the newly inserted documents _id field values. See the reference for an example.
To retrieve the inserted documents, query the collection:
> db.posts.find().pretty();
{
        "_id" : ObjectId("5e198ead41b7a7bd66f65982"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database",
        "by" : "Java Guides",
        "url" : "https://www.javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 500
}
{
        "_id" : ObjectId("5e198f8e41b7a7bd66f65983"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("5e198f8e41b7a7bd66f65984"),
        "title" : "NoSQL Database",
        "description" : "NoSQL database doesn't have tables",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 20,
        "comments" : [
                {
                        "user" : "user1",
                        "message" : "My first comment",
                        "dateCreated" : ISODate("2013-12-10T09:35:00Z"),
                        "like" : 0
                }
        ]
}

Insert Behavior

Collection Creation

If the collection does not currently exist, insert operations will create the collection.

_id Field

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.
This also applies to documents inserted through update operations with upsert: true.

Atomicity

All write operations in MongoDB are atomic on the level of a single document.

Comments