How to Insert Documents in MongoDB?

Since the mid-2000s, MongoDB has become one of the most popular document-oriented NoSQL databases It is used to store high volumes of data. Unlike SQL databases MongoDB uses collections and documents to store data. Collections are similar to tables in an SQL database, and documents are similar to rows in the table.  

In this blog you will learn about documents and collections and how to insert documents into a collection in MongoDB. 

Prerequisites   

This blog expects you to have latest MongoDB installed in your local machine. If you do not, then please download and install from here

As mentioned earlier collections are similar to tables in an SQL database, and they store documents in a similar manner to rows in the table. Please note that the documents are not required to have the same structure as MongoDB as it is a schema free database. Documents inside collection may have different fields.  

Documents in MongoDB are the basic units of data which we store in collections. They look like JSON objects but inside the database they exist in a more type-rich format called as BSON. They are similar to rows in an SQL database.  

To start the mongo server or mongo daemon, give the command in terminal or command prompt or PowerShell, whichever is convenient for you based on your operating system, and run the below command. 

Command: mongodHow to insert documents in MongoDB

Now open the new window of the same terminal or command prompt or PowerShell and give the below command to open up mongoshell where we run our commands. 

Command: mongo 

To insert documents, we need to switch to a database. Use the following command to switch to a database. 

Command: use exampleDBHow to insert documents in MongoDB

To insert documents into a collection we use different methodsLet’s look at them one by one. 

To insert documents into the collection we use MongoDB insert() method. The syntax is as shown below. 

Note that we can insert single and multiple documents using this method. To insert single document, we give that specific document as argument to the insert method. When we want to insert multiple documents, we need to provide the array of the documents as shown in the below example. 

Syntax: db.COLLECTION_NAME.insert(< document or array of documents>) 

To insert document into the database run the below command: 

Command: db.users.insert({name: “sai”, age: 25})  How to insert documents in MongoDB

To insert multiple documents into the database run the below command: 

Commanddb.users.insert([{name: “chandra”, age: 26}, {name: “jaya”, age: 20},{name: “surya”, age: 23}])How to insert documents in MongoDB

Let’s cross check for the successful insertion of the documents. To do so we need to use find() method as shown below. 

Syntax: db.COLLECTION_NAME.find () 

Command: db.users.find()How to insert documents in MongoDB

You can see all the documents we have inserted using insert method. 

To insert single document, we need to use insertOne() method. The syntax is as shown below. 

Syntax: db.COLLECTION_NAME.insertOne() 

To insert a document using insertOne method into the users collectionrun below command: 

Command: db.users.insertOne({name: “srujan”, age: 27})How to insert documents in MongoDB

To insert multiple documents into the collection, we need to use insertMany() method. The syntax is as shown below. 

Syntax: db.COLLECTION_NAME.insertMany() 

To insert multiple documents, using insertMany method into the users collection, run the below command: 

Command: db.users.insertMany([{name: “kiran”, age: 30}, {name: “kumar”, age: 28}]) How to insert documents in MongoDB

We can crosscheck with find(method.How to insert documents in MongoDB

We can also view the documents in a very informative way. We can use JSON view and Field-by-Field Editor to view the documents. 

JSON view 

To view the documents in a JSON view you need to use find method which we have used above in a slightly different syntax, as shown below. 

Syntax: db.COLLECTION_NAME.find().forEach(printjson) 

Let’s look at our users example. To do so run the below command in the mongo shell. 

Command: db.users.find().forEach(printjson)How to insert documents in MongoDB

All the documents can be viewed in a very structured way, in the same manner as JSON documents. 

Field-by-Field Editors are the applications which enable us to view the MongoDB databases in a Graphical User Interface (GUI). These applications enable us to edit the documents field by field within them. They are similar to the SQL Server for the SQL databases.  

Some famous ones for MongoDB are Robo3T and MongoDB Compass. 

Download Robo3T from here

Download MongoDB Compass from here

Please note that the MongoDB Compass is officially recommended by MongoDBMoreover, its developed by MongoDB itself so we will look at MongoDB Compass in this blog. 

After downloading and installing compass, open it and click on New Connection. Enter localhost as Hostname and 27017 as Port and then click on connect as shown in below images. How to insert documents in MongoDBHow to insert documents in MongoDB

How to insert documents in MongoDB

This takes us to the list of databases. Select exampleDB as we are using the same in this blog.How to insert documents in MongoDB

This takes us to the list of collections. Select the users collection as we are using the same in this blog.   How to insert documents in MongoDB

This takes us to all the documents we have inserted so far in the above examples into this collection.     How to insert documents in MongoDB

Here you can see all the documents and edit them as well. 

Insert Documents using a For Loop 

MongoDB also offers flexibility to do bulk document insertion using a for loop. To achieve this, we will use insert() method we learnt above but within a for loop. This method is used to insert bulk amounts of data into the collection. 

For this example, lets create a new collection instead of using users collection.  

Run the below command to insert documents using a for loop. 

Command: 

How to insert documents in MongoDB

Now let’s verify the results in JSON view as well as in MongoDB compass. 

To view the result in JSON view, run the below command in mongo shell. 

Command: 

How to insert documents in MongoDB

To view the result in compass, select testCollection within the compass and you can see all the documents inside the collection.  How to insert documents in MongoDB

However, it’s also important to know about the behaviour of all the insert methods we have learnt so far. They include: 

We also have limitations for when we are creating a collection or creating a database or when inserting a document. The important ones are given below. 

Read more about all the limitations over here

In this blog we have learnt about collections and documents, different methods to insert a document into the collection along with some examples, different methods to view the collections and the behaviour and limitations in creating the collections and documents. 

To become a skilled Mongo developer and learn by doing, check out our immersive learning course here. 

  • Write ConcernAll the methods use insert Command under the hoodRead more about the insert command over here
  • Create Collection: If the collection does not exist, then all the methods we learnt will create a new collection. 
  • _id FieldIf the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId() for the document before inserting. Read about ObjectID over here
  • TransactionsAll the methods can be used inside multi-document transactions. Read more about transactions over here 
  • BSON Document SizeThe maximum BSON document size is 16 megabytes. 
  • Nested Depth for BSON Documents: MongoDB supports no more than 100 levels of nesting for BSON documents. 
  • Database Name Case Sensitivity: Since database names are case insensitive in MongoDB, database names cannot differ only by the case of the characters. 
  • Length of Database NamesDatabase names cannot be empty and must have fewer than 64 characters. 
  • Restriction on Collection Names: Collection names should begin with an underscore or a letter character, and cannot: 
    • contain the $. 
    • be an empty string (e.g. “”). 
    • contain the null character. 
    • begin with the system. prefix. (Reserved for internal use.) 
  • contain the $. 
  • be an empty string (e.g. “”). 
  • contain the null character. 
  • begin with the system. prefix. (Reserved for internal use.) 
  • Research & References of How to Insert Documents in MongoDB?|A&C Accounting And Tax Services
    Source

    error: Content is protected !!