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.
Now that you have installed the mongo shell. Let's have a look at the most commonly used mongo query.
- 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>
- 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
- Export only one MongoDB collection
mongodump --uri mongo_uri_with/dbname --collection collection_name
- Restore whole MongoDB database
mongorestore -d <db-name> .\path\to\dump --uri_mongo_uri
- Restore only one MongoDB collection
mongorestore -d <db-name> .\dump\file\collection_name.bson --collection collection_name --uri mongo_uri
- 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.
- 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} }
]
- Update a field/column name in all documents
db.users.updateMany(
{ },
{ $rename: { "username" : "userName" } }
);
- Insert a new field in all documents
db.users.update(
{ },
{ $set:{ <NEW_FIELD_NAME>:<NEW_FIELD_VALUE> } },
{ upsert: false, multi: true }
);
- 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.