Cheatsheet of useful MongoDB command line commands

In this article we have listed few yet very useful and very commonly used MongoDB commands. This article is not a tutorial on MongoDB but a list of useful commands for MongoDB; so this is kind of cheatsheet of MongoDB commands.

How to take backup of MongoDB database

Run the below command in command prompt

mongodump -d db_name -o /path/to/dir

If database db_name doesn’ exist then it’ll be created.

How to restore MongoDB database backup dump

The above command to create backup will create a directory by the name of database. This directory will contain number of bson and json files depending upon the number of collections in your database. To restore this dump you’ll have to run the below command in command prompt. In this command you need to specify the path of the directory (by name of your database)

mongorestore -d db_name /path/to/dir/containing/backup/files

If database db_name doesn’ exist then it’ll be created.

How to export a MongoDB Collection to csv file

mongoexport --host hostname --db db_name --collection collection_name --type=csv --out text.csv --fields column_1,column_2,column_3

Before running the above command make sure you cd to directory where you want to generate csv file.

Leave a Reply

Your email address will not be published. Required fields are marked *