MongoDB most commonly used commands and queries

MongoDB most commonly used commands and queries

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

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>@<db-name>

2. Export or dump the whole MongoDB database

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

To exclude some collections, you can use multiple --excludeCollection=collection_name flag

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

	{ }, 
	{ $rename: { "username" : "userName" } }

9. Insert a new field in all documents

	{ },
	{ upsert: false, multi: true }

10. Quickly find documents with array size. Let's say you want to fetch documents with at least 2 elements in the array field. Then you can use "field_name.1":{ $exists:true }

db.users.find({ "field_name.1":{$exists:true} })

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