MongoDB most commonly used commands and queries

Posted on Jun 05, 2021 ‐ 3 min read

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>
  1. Export or dump the whole MongoDB database
mongodump --uri mongodb://<username>:<password>@12.34.56.789:27017/<db-name>

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

  1. Export only one MongoDB collection
mongodump --uri mongo_uri_with/dbname --collection collection_name
  1. Restore whole MongoDB database
mongorestore -d <db-name> .\path\to\dump --uri_mongo_uri
  1. Restore only one MongoDB collection
mongorestore -d <db-name> .\dump\file\collection_name.bson --collection collection_name --uri mongo_uri
  1. 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.

  1. 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} }
]
  1. Update a field/column name in all documents
db.users.updateMany(
  { }, 
  { $rename: { "username" : "userName" } }
);
  1. Insert a new field in all documents
db.users.update(
  { },
  { $set:{ <NEW_FIELD_NAME>:<NEW_FIELD_VALUE> } },
  { upsert: false, multi: true }
);
  1. 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 tweet me at @vip_iny.