Before we start, we need the mongo shell installed on our system. If you have already installed the MongoDB Server, the mongo shell is installed with it. If you just want the command line shell then download it from the MongoDB official website. Browse to the installed bin folder in terminal or if you are on Windows 10 then, add the path to bin folder in your environment variables.

Verify the shell installation by running mongo --version command. If you see the below output then, mongo shell is installed correctly.

Mongo shell installation

Now that you have installed the mongo shell. Let's have a look at the most commonly used mongo query.

1. Login to MongoDB server using mongo shell

mongo -u <username> -p --authenticationDatabase <db-name> --host 12.34.56.789

This command will prompt for password on the next line. If you have the MongoDB uri then you can directly use it with mongo.

mongo mongodb://<username>:<password>@12.34.56.789:27017/<db-name>

2. Export or dump the whole MongoDB database

mongodump --uri mongodb://<username>:<password>@12.34.56.789:27017/<db-name>

3. Export only one MongoDB collection

mongodump --uri <uri with /db> --collection <collection-name>

4. Restore whole MongoDB database

mongorestore -d <db-name> .\path\to\dump --uri <mongo-uri>  

5. Restore only one MongoDB collection

mongorestore -d <db-name> .\dump\file\<collection-name>.bson --collection <collection-name> --uri <mongo-uri>

6. Export MongoDB collection in csv format

mongoexport --uri="<mongo-uri>" --collection <collection-name> --type=csv --fields="_id,firstName,lastName,email" --query='{}' -o <file-name>.csv

You can specify the find query by using --query flag to filter the output result or omit the --fields flag to export all the fields.

7. Find duplicate fields in other documents

Create an aggregate query and use the below group, match and project stage to show the duplicate fields across all documents. Just replace the FIELD_NAME value to your field name that you are looking.

[
    {"$group" : { "_id": "$<FIELD_NAME>", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } },
    {"$project": {"<FIELD_NAME>" : "$_id", "_id" : 0} }
]

8. Update a field/column name in all documents

db.users.updateMany(
	{ }, 
	{ $rename: { "username" : "userName" } }
);

9. Insert a new field in all documetns

db.users.update(
	{ },
	{ $set:{ <NEW-FIELD-NAME>:<NEW-FIELD-VALUE> } },
	{ upsert: false, multi: true }
);

If you know any other commonly used queries then tell me in the comments below or tweet me at @vipiny35.