As we already know that MongoDB is a document store that is it stores data in documents. Let us start creating documents in MongoDB and learn about collections and databases while doing that.


We need to start MongoDB shell for this tutorial. You can open a command prompt start MongoDB server in it by typing mongod. Then we can open another command prompt and type “mongo”. This starts MongoDB shell. If you do not have MongoDB installed on your system, you can read this article and configure it.

Databases and collections:

We need some way so that we can store similar kinds of the document in the same place in MongoDB. This is achieved by collections. Collections in MongoDB are like tables in Relational Databases.

MongoDB keeps collections grouped in different databases. To query MongoDB record, we need to know its database as well as collection. We can see databases in MongoDB using following command. It will show you call the databases present in the server along with their memory size.

We can select one of this database using the command “use dbName”. We can see all the collections in that database using the following command.

This shows that the user database has a collection named users. Please note that this database and collection is created by me for testing purpose. You may not see them on your MongoDB server.

Creating Document in MongoDB

Now let us create our first document in MongoDB. We can use insert command for this. This command inserts a record in a collection named students. If students collection does not exist, it creates this collection. If this is the first record in this collection, then it also creates a document inside students collection.

We can validate if this document is successfully stored or not.

As mentioned in the previous article, all documents in MongoDB must contain _id filed. This is the unique identifier for each document within the collection. You can think of it as a primary key in relational databases.

Let us insert another document in a collection and check the count of all documents.

We can see that our collection has two documents. Using find command we can list both of these documents.

On a side note, if you get the reference of names John Markson and Mark Johnson kudos to you !!! 🙂

Inserting document with a _id value

We can set _id value for the document while inserting it into a collection. We need to ensure that it is a unique value for that collection.

Here, We were able to insert Mark Johnson again because it has different _id value.

Inserting multiple documents

We can insert multiple documents in a single command. We can pass an array of documents to insert function which inserts these values into the collection.


We have learned how to create document and collection in MongoDB. We have inserted our first document, learned how to insert a document with preset _id field and bulk insert. See you next time, till then keep learning.


Leave a Reply

Close Menu