Getting Started With MongoDB (Part 2)

DZone 's Guide to

Getting Started With MongoDB (Part 2)

Learn how to perform various CRUD operations in MongoDB using MongoShell.

· Database Zone ·
Free Resource

Hello everyone! In my previous article, I explained what MongoDB is and why you should use it. In this article, I will try to explain CRUD operations in MongoDB using MongoShell.

To check available databases:

>show dbs

This command will show you a list of all available databases.


To create a database in MongoDB:


Here, DATABASE_NAME represents the name of the database that you want to create.

To check the current database:


To create a collection in database: 


Image title

Here, db refers to the database that you are using.

To check available collections:



To insert a document in a collection, there are a few options.

  1. To insert one document:


2. To insert many documents:



Here, you can see that we inserted two documents at a time and the acknowledgment of the inserted document was returned. You also notice that it returns _id, which is the unique id that is set by MongoDB. You can read more about the primary key(_id) in my previous article.

To retrieve all data from the collection:



To retrieve the data that satisfy the condition:


In the example given below, the condition applied is: Name should be “shubham”.


Retrieve only one document:


This returns one document that satisfies the specified query criteria on the collection or view. If multiple documents satisfy the query, this method returns the first document according to the natural order that reflects the order of documents on the disk.

To update a document (MongoDB uses the update() method for updating a document that accepts two arguments):

  1. A document in which you need to define the condition for updating the document.

  2. A document that contains the fields that need to be updated.



Note: When the updated condition meets more than one document, MongoDB updates only one document. For updating all the documents that satisfy the condition, you have to set the value of the field multi as true.


  • To remove document in MongoDB:
  • To remove document by condition:


I hope this article helps you to do some basic operations on MongoDB. In my next article, I will explain more operations like sorting, aggregation, etc. 

crud ,database ,mongodb ,mongoshell ,tutorial

Published at DZone with permission of Shubham Agarwal , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}