From charlesreid1

Link to useful cheat sheet: https://mindmajix.com/mongodb-commands


Connecting

To figure out what's in a mongodb database, start by figuring out where mong is running and how to connect to it:

ps aux | grep mongo

This will show the currently-running mongo process and the command used to start it, which will tell you what port mongo is listening on. Suppose it's running on port 12121. Then we can connect to the mongo db this way:

mongo --port 12121

This will give us a shell prompt for the mongo db shell.

Exploring

Show dbs

Start by figuring out what databases there are. Run the listDatabases command this way:

> db.adminCommand({listDatabases: 1})

alternatively, the shortcut:

> show dbs

Use dbs

Pick a database to use from the ones listed:

> use elfu

Now you can use the name of the db instead of the literal variable db

Show collections in that db:

> show collections

Show all the roles in the db:

> show roles


Find Some Records

To find some records, use the find() command and give it the name of a collection in a database to search.

For example, suppose I chose to use the elfu database, and from there I printed the collections and saw a collection named solution

Now I can search for a single item in that collection, by doing this:

> use elfu
> db.solution.findOne({})

This runs a find with no fields specified (wildcard search) but limits the number of results to one.