• Articles
  • Tutorials
  • Interview Questions

How to Create a Database in MongoDB in 5 Minutes?

What is a Database Command in MongoDB?

Database commands are like helper functions that allow us to write/send the data to the database. These commands are also used to modify the structure or documents that are present inside the database and helps in MongoDB create database.

We will look at some important commands which are MongoDB sort command, MongoDB find command, etc.

Before we start learning the MongoDB create database commands, let’s have a look at the entire tutorial outline.

Kick-start your career in MongoDB with the perfect MongoDB Training Course now!

Database Creation Using MongoDB Insert Command

The most important part of MongoDB create database is MongoDB insert command to insert data into MongoDB collection. We can use two methods here; they are insert() or save()methods.

Syntax

The basic syntax of MongoDB insert command is as follows:

db.COLLECTION_NAME.insert(document)

Example

mongodb insert - Intellipaat

In the above code, mycommand is the name of our MongoDB collection. If the collection doesn’t exist in the database, then MongoDB creates the collection itself and then inserts a document into it.

In the MongoDB document that we have inserted, if we don’t specify the _id parameter, then MongoDB assigns a unique ObjectId for this document by default.
Let me tell you about the _id. It is a 12-byte hexadecimal number unique for every document in a collection. 12 bytes are divided as follows:

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

Let’s see an example of code with _id:

db.mycommand.insert({
    _id: ObjectId(7df78ad8902c),
    title: 'MongoDB Overview', 
    description: 'MongoDB is no sql database',
    by: 'Intellipaat',
    url: 'http://www.intellipaat.com',
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 100
})

As we have inserted the data into MongoDB collection, now we will see how to view the inserted data. To view the inserted data in MongoDB create database, we will use the following command:

db.mycol.find().pretty()

The find() command will give us our data and the pretty() command is used to display the result in a formatted way.

Further in this tutorial, we will cover MongoDB find command in detail.

mongodb find command - Intellipaat

Get familiar with the top MongoDB Interview Questions to get a head start in your career!

Primary Key in MongoDB

Now, we will discuss the primary key in the MongoDB create database. The _id field works as the primary key for the MongoDB collection so that each document can be uniquely identified in the collection. There is a unique ObjectId value associated with each _id field by default, which is a hexadecimal number.

However, we do not need to worry about inserting the primary key in our queries because, by default, when inserting documents in MongoDB collection, if you forget to add a field name with the _id, then MongoDB automatically handles the situation and adds an ObjectId field as shown below:

mongodb primary key - Intellipaat

mongodb primary keyword - Intellipaat

In the above code, we have not mentioned the _id field, but when we run that code the _id appears by default in the output of the code.

MongoDB Limit and MongoDB Sort Commands

For modifying the queries, MongoDB provides query modifiers that are limit() and sort() clauses. These provide more flexibility when executing queries. We will have a look at these query modifiers.

Become a Database Architect

MongoDB Limit Command

MongoDB limit is used to limit the number of documents that are returned in the result set for a query. Below is an example that shows how this can be done.

db.mycommand.find().limit(2).forEach(printjson)

The above code takes the find function that returns all the documents created by MongoDB create database in the MongoDB collection. But, the limit clause in the code limits the number of documents being returned to just 2.

mongodb limit command - Intellipaat

MongoDB Sort Command

The MongoDB sort command is used to specify the order of documents to be returned based on an ascending or descending order of any key in MongoDB collection. Below is an example which shows how this can be done.

db.mycommand.find().sort({mycommandid:-1}).forEach(printjson);

The above code is using the MongoDB sort function that returns all the documents in MongoDB collection, but then it is using the modifier to change the order in which the records are returned. The number ‘-1’ in the above code indicates that we need to return the documents based on the descending order of mycommandid.

Let’s see the live code below:

mongodb sort command - Intellipaat

 

MongoDB Find Command

We use MongoDB find method to query data from MongoDB collection.

Syntax

The basic syntax of the find() method is as follows:

db.COLLECTION_NAME.find()

As we have mentioned earlier, the MongoDB find method will display all the documents in a non-structured way.

Another method we use with our MongoDB find method is the pretty() Method. The pretty() method is used to display the results in a formatted way.

Syntax for the Find with Pretty Command

The syntax of the find() command with the pretty() command is as given below:

db.mycol.find().pretty()

Example

mongodb preety command - Intellipaat

Apart from the find() method, there is yet another method, which is the findOne() method that returns only one document.

To have a detailed comparison between Firebase and MongoDB, check out Firebase Vs MongoDB!

MongoDB Update Command

The MongoDB update method is used to update the MongoDB document into a collection. The update method updates the values in the existing document.

Syntax

The basic syntax of the update() method is as follows:

db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)

Example

First, we will create a database with some details. Next, we will change the name, and then we will use the update command to see whether our database has been updated or not.

mongodb update command - Intellipaat

After creating our first database, we got the following output.

mongodb update command - Intellipaat

Now, we will update it with the update method.

update command - Intellipaat

Here is our updated data as given below. We can see that all the values have been changed.

output mongodb update command - Intellipaat

Intellipaat provides the best Database Courses for its learners.

MongoDB Count and Remove Commands

MongoDB Count Command

MongoDB provides the count() function that is used to know the count of documents in a collection as per the query fired.

 db.mycommand.count()

mongodb count command - Intellipaat

We can see that the output comes as ‘4’, i.e., the number of documents in the MongoDB collection is 4.

MongoDB Remove Command

To remove documents from a MongoDB collection, MongoDB uses the remove() method. This command either removes all of the documents from a collection or only those that match a specific condition.

If we just issue the remove command, then all documents will be removed from the collection.

Syntax

The syntax for the remove method is as follows:

db.collection.remove()

Example

The following example demonstrates how to remove documents from a collection named as ‘university’:

db.university.remove({})

The below example shows how we can remove a specific document from the collection ‘university’:

db.university.remove({some_condition})

First, we will create a database named as ‘student’ with some details.

remove command - Intellipaat

The database is created successfully. Now, we will run db.student.remove({})and see whether it removes the database or not.

remove command - Intellipaat

And here we go! The remove command has removed the database from the database.

Learn more about NoSQL from this insightful NoSQL blog!

Concept of MongoDB Cursor

When we search for a document in a collection using the db.collection.find () function, as a result, a pointer to the collection of documents gets returned, which is called a cursor.

By default, the cursor will be iterated automatically when the result of the query is returned. However, we can also explicitly go through the items returned in the cursor one by one.

Example

If we have three documents in our collection, the cursor object will point to the first document and then iterate through all of the documents of the collection.

cursor - Intellipaat

MongoDB cursor has many important methods; one of them is mentioned below (To see all other methods, you can visit the official website of MongoDB).

cursor.explain()

The cursor.explain method explains everything in our database individually. Below is an example that shows when we run cursor.explain(), it explains everything that our database contains.cursor - IntellipaatWe have learned a lot in this tutorial starting with the important features of MongoDB and further learning various MongoDB commands with their live examples. I hope this tutorial has helped you knowing MongoDB better and choosing the right path for a lucrative career.

Know more about the management tools in MongoDB in this MongoDB Tutorial!.

Course Schedule

Name Date Details
No Sql Course 05 Oct 2024(Sat-Sun) Weekend Batch
View Details
No Sql Course 12 Oct 2024(Sat-Sun) Weekend Batch
View Details
No Sql Course 19 Oct 2024(Sat-Sun) Weekend Batch
View Details

About the Author

Techical Research Analyst - Front End Development

As a Technical Research Analyst, Kislaya specializes in Front End Development. He is a Full Stack Developer, known for crafting scalable architectures and user-centric interfaces. He has a massive international client base and is an expert in cloud computing, Linux, and Java Script, personifying a commitment to quality and information sharing.