MongoDB - Java

MongoDB - PHP

MongoDB - Advanced

MongoDB - Useful Resources

MongoDB - Insert Document



In this chapter, we will learn how to insert document in MongoDB collection.

The insertOne() method

If you need to insert only one document into a collection you can use this method.

Syntax

The basic syntax of insert() command is as follows −

>db.COLLECTION_NAME.insertOne(document)

In the inserted document, if we don't specify the _id parameter, then MongoDB assigns a unique ObjectId for this document.

_id is 12 bytes hexadecimal number unique for every document in a collection. 12 bytes are divided as follows −

_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)

Example

Following example creates a new collection named empDetails and inserts a document using the insertOne() method.

test> db.createCollection("empDetails")
{ "ok" : 1 }

Insert a Document in the collection

test> db.empDetails.insertOne(
...     {
...             First_Name: "Radhika",
...             Last_Name: "Sharma",
...             Date_Of_Birth: "1995-09-26",
...             e_mail: "radhika_sharma.123@gmail.com",
...             phone: "9848022338"
...     })
{
  acknowledged: true,
  insertedId: ObjectId('6964b6ee25c4ea6b911e2625')
}
test>

The insertMany() method

You can insert multiple documents using the insertMany() method. To this method you need to pass an array of documents.

Example

Following example inserts three different documents into the empDetails collection using the insertMany() method.

test> db.empDetails.insertMany(
...     [
...             {
...                     First_Name: "Radhika",
...                     Last_Name: "Sharma",
...                     Date_Of_Birth: "1995-09-26",
...                     e_mail: "radhika_sharma.123@gmail.com",
...                     phone: "9000012345"
...             },
...             {
...                     First_Name: "Rachel",
...                     Last_Name: "Christopher",
...                     Date_Of_Birth: "1990-02-16",
...                     e_mail: "Rachel_Christopher.123@gmail.com",
...                     phone: "9000054321"
...             },
...             {
...                     First_Name: "Fathima",
...                     Last_Name: "Sheik",
...                     Date_Of_Birth: "1990-02-16",
...                     e_mail: "Fathima_Sheik.123@gmail.com",
...                     phone: "9000054321"
...             }
...     ]
... )
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId('6964b72125c4ea6b911e2626'),
    '1': ObjectId('6964b72125c4ea6b911e2627'),
    '2': ObjectId('6964b72125c4ea6b911e2628')
  }
}
test>
Advertisements