We earn commission when you buy through affiliate links.

This does not influence our reviews or recommendations.Learn more.

Users are generating structured, semi-structured, and unstructured data in an unlimited amount.

What is MongoDB?

MongoDB is a document-oriented, cross-platform and open-source NoSQL Database used to store semi-structured data written in C++.

Instead of tables and rows, MongoDB stores data in key-value pairs.

Lets get it started.

Basic Commands

1.

Version check

The foremost command is to check the installed version of the MongoDB server and Mongo Shell.

Run this command on the terminal on Linux or CMD prompt on windows.

mongod –version

We can also usemongodcommand to check the version, as follows.

mongo version

2. fire off the command on Mongo Shell.

help()

3. db.stats()

4.

In MongoDB test is default database hence users use test DB once Mongo Shell is logged in.

use DB_Name

5.

Listing all the Databases

The mentioned command is being used to list all the databases.

show dbs

6.

Check the DB currently in use

Run below command on Mongo Shell to see the DB currently in use.

db

7.

Drop Database

The given command helps the user to drop the required database.

execute the command on MongoDB client.

yo double-check to go for the Database before running the drop command.

Otherwise, it will drop the default test Database.

Create Collection

Collections are similar to tables in RDBMS.

Create a collection command consists of two parameters.

The collection consists of zero or more documents.

The capped collection has a property to remove the oldest documents to make space for new documents.

Drop Collection

Drop Collection command is similar to DDL in RDBMS.

It acquires locks on the required collection until the execution of the command.

Drop collection removes the collection from the DB along with all the indexes associated with that collection.

To drop the collection drop() method is required.

It returns true for successful drop and false in case of any error or if DB doesnt exist.

Syntax:collectionName.drop()

10.

Insert Document into Collection

In MongoDB document is similar to a tuple in RDBMS.

To create a document, theinsert()method is used.

The insert() method creates one or many documents in the existing collection.

It also creates collection if it is not present in DB.

To insert one recordinsert()orinsertOne()method can be used.

The below command will be used to retrieve all the documents from the collection.

Beautify Retrieval output

Thefind()method gives a disorganized output.

MongoDB providespretty()commands to get the formatted output.

Syntax:collectionName.find().pretty()

13.

Update Document in a Collection

MongoDB providesupdate()method to set new values for existing keys in documents.

Update command gives details of modified and matched documents.

Delete Document of a Collection

To delete the document, MongoDB consist ofdeleteOne()anddeleteMany()methods.

Retrieve Distinct

Thedistinct()method is used to get unique records.

Syntax:collectionName.distinct(field)

Syntax:collectionName.distinct(field,query)

16.

Rename collection

MongoDB providesrenameCollection ()method to rename collection.

Syntax:collectionName.renameCollection(newCollectionName)

Indexing

17.

Indexes support ascending and descending ordering of fields values and hence facilitate better performance while retrieval.

Also, MongoDB supports the creation of user-defined Indexes.

MongoDB indexes are defined at collections level and it provides supports at field or sub-field of a document.

To create an index in descending order -1 can be used.

Show Index on Document

MongoDB providesgetIndexes()method to list all the indexes created on a document.

Syntax:collectionName.getIndexes()

19.

Limit retrieval of documents

limit()method helps to limit the number of documents returned.

The limit() method accepts numerical arguments.

Syntax:collectionName.find().limit(number)

21.

Skip retrieval of documents

MongoDB supportsskip()method.

This method skips the required number of documents.

It accepts a numeric argument.

Syntax:collectionName.find().skip(number)

22.

Sort retrieval of documents

MongoDBsort()method sort the output documents either in ascending or descending order.

Document validation

Validators help to restrict the bang out of data being inserted in the documents.

Validators are defined on collection.

Validator creation is required to use keywordvalidatorand optionalvalidation levelandvalidation actionto specify the validation mode.

Document validation doesnt restrict the insertion of the new field in the document.

It prevents new fields to be added in the document.

Without specifying the collection namedb.getCollectionInfos()method gives details of validators on all collections residing inside a DB.

Cursor in MongoDB

The cursor is a pointer to iterate over the result set.

A list ofcursor methodshas been provided.

Examples:

Utility

29.

Taking a database backup

mongodumputility is used to export the content of the MongoDB database as a backup.

This command runs from system console and not from mongo shell.

It will generate binary backup along with metadata information.

Syntax:mongorestore –db newDB “pathOfOldBackup”

31.

Exporting collections

To export content of collection to a file (JSON or CSV)mongoexportutility has been provided.

To run this command use system terminal.

Importing collections

To import data from file (CSV or JSON)mongoimportcommand-line tool can be used.

MongoDB Replication

Replication is the process to synchronize data on multiple servers.

It prevents data loss due to hardware or software malfunctioning.

MongoDB achieves replication using Replica sets.

The replica set consists of Primary and secondary Mongo data sets in the cluster.

Primary Data set accepts all write operations and secondary data set reads from Primary.

Minimum 3 data sets are required in Mongo Replica set.

rs.conf()

rs.status()

35.

Syntax:rs.remove(“localhost:27017”)

37.

Syntax:rs.stepDown( stepDownSecs , secondaryCatchupSecs )

38.

Syntax:rs.printSlaveReplicationInfo()

39.

Transactions in MongoDB

MongoDB supports ACID properties for transactions on documents.

Transactions are supported on replica set or mangos.

Once the session committed successfully, operations made inside the session will be visible outside.

Single Document Transactions Conflict

If two transactions tried to update the same document, MongoDB throws write conflict error.

Perform some insert/update on Session1 followed by on Session2.

Now observe the error in the below example

41.

Multi-Document Transactions

MongoDB support multi-document transactions in a single session.

Perform some insert/update on multiple documents

42.

It returns results as per theverbosity plan.

44.

Access Control in MongoDB

Access control features enable authentication access to existing users.

For access control enabled DB to ensure to create a user admin role in admin DB.

Revoke User-defined Roles

To modify the existing roles use below command.

MongoDB Connectivity with Python

The pymongo package is required to connect MongoDB from python Console.

Check out this list ofNoSQL clientsto manage MongoDB and other NoSQL databases.

If your job involves frequently working on MongoDB then you may want to learn more from thisUdemy course.