The following is my personal MongoDB Cheat Sheet
Backups and Restores
Sometimes you need to migrate your database from one instance to another, I usually need to take a copy of the staging db into my local instance.
Mongodump
The simplest way to get the data is to use mongodump command on the cli.
mongodump "mongodb+srv://url.or.hostname.of.mongodbhost/" --username exampleuser
This will create a binary dump of the database in the dump/name-of-db folder.
Mongorestore
To restore the dump to my local database, all I need to do is the following.
cd dump
mongorestore --db=name-of-localdb- example-name-of-db
Retrieving/Querying the Data
I like to use the MongoDB Compass Application made by the Mongo folks to query the data. You can download it by visiting https://www.mongodb.com/try/download/compass.
Find a specific record in MongoDB
Compass makes it really easy to get a grasp of what’s in the db, but when you have thousands of records and need to search for a specific one, you need write a query.
Let’s assume we have a collection called users
Please note, that the examples below are when you’re using mongosh, but if you’re using the Compass GUI, you can skip the db.users.find() part, and just use the string inside the parentheses including the curly brackets { }
Search for a specific record
Let’s search the users table for records where the email address is [[email protected]]
db.users.find( { email: "[email protected]" } )
Searching with wildcards
Say you want to modify your search and find all records where the email field contains @atestpage.com
db.users.find({ "email": { $regex: /@atestpage.com/, $options: 'i' } })
Sorting
What if you want this list with the newest records first? Assuming you have a field called createdAt in the table..
db.users.find({ "email": { $regex: /@atestpage.com/, $options: 'i' } }).sort({ "createdAt": -1 })
Group and Count
What if you need to get a breakdown of users based on the status field in the collection. If you’re used to SQL, you’ll do something like the following.
SELECT status, count(status) as num_records from users GROUP BY status;
+----------------------+-------------+
| status | num_records |
+----------------------+-------------+
| active | 3 |
| waitlisted | 2 |
+----------------------+-------------+
In MongoDB this is called an “Aggregation”. You can click the tab in the Compass UI and play with the wizard, it’s fairly easy to use, but if you are in MongoSH do the following.
db.users.aggregate([ { $group : {_id:"$status", count:{$sum:1}}} ])