MongoDB – Insert Document

Themomsco [CPS] IN

MongoDB Insert Document:

In this tutorial, we will learn how to insert documents into a collection. We are going to use multiple examples to make you understand in a simple way.

In MongoDB, there are three methods available for inserting documents into a collection.

  • insert()
  • insertOne()
  • insertMany()

If you do not have MongoDB installed on your computer, learn using the below links:

We will understand each method in details with the example below:

Method 1: MongoDB insert()

MongoDB Insert Document using insert() Example

Syntax: db.COLLECTION_NAME.insert(document)

db.users.insert({
   name: 'Techy Hunger', 
   email: 'techyhunger@gmail.com'
   website: 'https://www.techyhunger.com',
   topics: ['mongodb', 'angular', 'node']
})

In the above code block, we have inserted a document into the collection name ‘users’. And you can see there is a key named ‘topics’ which value is defined as an array.

Same way, we can set a field value as a simple object or a multi nested object of an array. e.g –

skills: [ {name: "NodeJs", experience: "4 years"}, {name: "Angular", experience: "3 years"}, {name: "Python", experience: "5 years"} ]

After running the command it prints:

WriteResult({ "nInserted" : 1 })

Note: At the time of inserting document the insert() method creates the collection in the fly if it not exists or uses the existing collection if it exists.

MongoDB Insert Document

you can also verify the document is successfully inserted into collection or not.

Syntax: db.COLLECTION_NAME.find();

To do that run the following command and you will get the all inserted documents of the “users” collection.

db.users.find()

and the output will be:

{
  "_id": ObjectId("5d42c7eb6ae908880a0f61a8"),
  "name": "Techy Hunger",
  "email": "techyhunger@gmail.com",
  "website": "https://www.techyhunger.com",
  "topics": [
    "mongodb",
    "angular",
    "node"
  ],
  "skills": [
    {
      "name": "NodeJs",
      "experience": "4 years"
    },
    {
      "name": "Angular",
      "experience": "3 years"
    },
    {
      "name": "Python",
      "experience": "5 years"
    }
  ]
}

As you can see the above output contains a key “_id”. This key is generated by MongoDB itself if you do not provide the “_id” key.

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key.

The value of the “_id” is a 12 digit’s ObjectID value, which is made by the following:

  1. The first 4-byte of value represents the seconds since the Unix epoch
  2. The first 3-byte machine identifier
  3. The first 2-byte process id
  4. The first 3-byte counter, starting with a random value.

Method 2: MongoDB InsertOne()

MongoDB Insert Document Using InsertOne() Example

In MongoDB, To insert a single document into a collection you can use the insertOne() method.

You can use insertOne() in the same way as you do for insert() method but the output will be different after successful document insertion.

Check the code below:

> use db employee
> db.users.insertOne({ userName: "Tech User" })

{
  "acknowledged" : true,
  "insertedId" : ObjectId("5d42d2346ae908880a0f61a9")
}

You can also insert embedded documents as well as arrays of documents:

see the reference code below:

> db.users.insertOne({
    userName : "Embedded Tech user",
    skill : [
                {
                    name : "Ionic",
                    exp : "4 years"
                }, 
                {
                    name : "Java",
                    year : "5 years"
                }
            ]
})

{
  "acknowledged" : true,
  "insertedId" : ObjectId("5d42d41e6ae908880a0f61aa")
}

Method 3: MongoDB insertMany()

MongoDB Insert Document Using insertMany() Example

In MongoDB, To insert multiple documents into a collection you can use the insertMany() method.

Please see the code shown below:

db.users.insertMany(
   [
     { _id: 11, name: "Oliver", born: 19481 },
     { _id: 11, name: "William", born: 1982 },
     { _id: 12, name: "Thomas", born: 1983 },
     { _id: 13, name: "Noah", born: 1984 },
     { _id: 14, name: "Jack", born: 1985 },
     { _id: 15, name: "James", born: 1986 },
     { _id: 16, name: "Lucas", born: 1987 },
     { _id: 17, name: "Henry", born: 1988 },
   ]
)

The db.users.insertMany() method will insert all the documents into the users’ collection at once.

Finally, Insert document in MongoDB tutorial is over. Hope you liked it, Please share your thoughts in the comment box.

Themomsco [CPS] IN

Leave a Reply