Mongo shell commands to get you through the day
Tags: tutorial, mongodb, beginners
Published: 2022-05-01 16:39:12

I recently started a new job. The data store is [MongoDB](https://www.mongodb.com), which I have barely used before. This post aims to document what I've learnt to get me through the day. Please feel free to [tweet me](http://twitter.com/benmatselby) if there are discrepancies.

The first thing that I became aware of, is that there are/were two cli tools:

- The legacy `mongo` shell, which [was deprecated in MongoDB v5.0](https://www.mongodb.com/docs/manual/reference/program/mongo/).
- The new, and active, `mongosh` shell, which replaced `mongo`. The documentation for this shell is [here](https://www.mongodb.com/docs/mongodb-shell/).

This post will discuss `mongosh` and assume you have MongoDB running on your machine (or access to an instance).

## Connecting

If you're wanting to connect to a local database instance, then by running `mongosh` it will connect to `localhost` as default.

A more complete connection string would be:

```shell
mongosh "mongodb://localhost:27017" -u [user]
```

This will prompt for the password, so it's not stored in your `~/.[zsh|bash]_history` file.

Once you have connected, you can run `help` to get some basic commands:

```shell
> help

  Shell Help:

    use                Set current database
    show               'show databases'/'show dbs': Print a list of all available databases.
                       'show collections'/'show tables': Print a list of all collections for current database.
                       'show profile': Prints system.profile information.
                       'show users': Print a list of all users for current database.
                       'show roles': Print a list of all roles for current database.
                       'show log <type>': log for current connection, if type is not set uses 'global'
                       'show logs': Print all logs.

    exit               Quit the MongoDB shell with exit/exit()/.exit
    quit               Quit the MongoDB shell with quit/quit()
    Mongo              Create a new connection and return the Mongo object. Usage: new Mongo(URI, options [optional])
    connect            Create a new connection and return the Database object. Usage: connect(URI, username [optional], password [optional])
    it                 result of the last line evaluated; use to further iterate
    version            Shell version
    load               Loads and runs a JavaScript file into the current shell environment
    enableTelemetry    Enables collection of anonymous usage data to improve the mongosh CLI
    disableTelemetry   Disables collection of anonymous usage data to improve the mongosh CLI
    passwordPrompt     Prompts the user for a password
    sleep              Sleep for the specified number of milliseconds
    print              Prints the contents of an object to the output
    printjson          Alias for print()
    cls                Clears the screen like console.clear()
    isInteractive      Returns whether the shell will enter or has entered interactive mode

  For more information on usage: https://docs.mongodb.com/manual/reference/method
```

## Listing the databases

Using the output from `help`, let's list all the databases stored in the instance we are running on.

```shell
> show dbs
```

We want to be able to switch between the databases, so lets switch to the `admin` database.

```shell
> use admin
```

## Creating a database

So we have seen how to list databases, but we want to create a new one to store our data. To do this, we can run:

```shell
> use entertainment
```

You may notice that we are using the same `use` command. By switching to a non-existent database, the database will be created, when we create a collection.

## Deleting a database

_Note:_ I **do not** recommend testing this on production!

Make sure you are on the database you want to drop:

```shell
> use entertainment
switched to db entertainment
```

And then let's drop the database.

```shell
> db.dropDatabase()
{ ok: 1, dropped: 'entertainment' }
```

## Creating a collection

Using the commands from above, create a database called `entertainment` again. Then switch to that database. We now want to create a collection. Let's just make sure we are on the same page again. Let's check the name of the database we are both on.

```shell
> db.getName()
entertainment
```

Your output should match mine, `entertainment`. Now, let's create a collection called `films`.

```shell
> db.createCollection("films")
```

For further options/configuration on creating collections, please review [the docs](https://www.mongodb.com/docs/manual/reference/method/db.createCollection/).

## Showing collections

Let's see what collections we have in the `entertainment` database.

_Note:_ If you're coming from a SQL based background, `collections` are the MongoDB equivalent of `tables`.

```shell
> show collections
films
```

## Inserting documents

Now we have a database (`entertainment`), and a collection (`films`), let's create some documents.

```shell
> db.films.insertOne({ title: "The Big Lebowski", url: "https://en.wikipedia.org/wiki/The_Big_Lebowski" })
{
  acknowledged: true,
  insertedId: ObjectId("626eaad80dd6e8884b86fda3")
}
```

This has created a document in the `films` collection with two attributes: `title`, and `url`. Behind the scenes, MongoDB will add an additional attribute: `_id` which cannot be changed.

You can also create many documents at the same time.

```shell
> db.films.insertMany([{ title: "How to loose a guy in 10 days", url: "https://en.wikipedia.org/wiki/How_to_Lose_a_Guy_in_10_Days" },
{ title: "Father of the Bride", url: "https://www.imdb.com/title/tt0101862/" }])
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("626eaae00dd6e8884b86fda4"),
    '1': ObjectId("626eaae00dd6e8884b86fda5")
  }
}
```

For further options/configuration on inserting documents, please review [the docs](https://www.mongodb.com/docs/manual/reference/method/db.collection.insertOne/).

## Getting documents

We should now have three documents in our `films` collection, within the `entertainment` database. Let's check:

```shell
> db.films.find({})
[
  {
    _id: ObjectId("626eaad80dd6e8884b86fda3"),
    title: 'The Big Lebowski',
    url: 'https://en.wikipedia.org/wiki/The_Big_Lebowski'
  },
  {
    _id: ObjectId("626eaae00dd6e8884b86fda4"),
    title: 'How to loose a guy in 10 days',
    url: 'https://en.wikipedia.org/wiki/How_to_Lose_a_Guy_in_10_Days'
  },
  {
    _id: ObjectId("626eaae00dd6e8884b86fda5"),
    title: 'Father of the Bride',
    url: 'https://www.imdb.com/title/tt0101862/'
  }
]
```

## Filtering documents

It's unlikely that we always want to get all of the documents, so let's filter films with the word `the` in them:

```shell
> db.films.find({ title: { $regex: /the/i }})
```

You can see we have introduced a `$regex` keyword to provide a `SQL LIKE` command, if you're use to SQL.

If you know the id of the document:

```shell
> db.films.find({ _id: ObjectId("626eaae00dd6e8884b86fda5") })
[
  {
    _id: ObjectId("626eaae00dd6e8884b86fda5"),
    title: 'Father of the Bride',
    url: 'https://www.imdb.com/title/tt0101862/'
  }
]
```

You can see that we are returning an array of documents. But what if we just want the one document?

```shell
> db.films.findOne({ _id: ObjectId("626eaae00dd6e8884b86fda5") })
{
  _id: ObjectId("626eaae00dd6e8884b86fda5"),
  title: 'Father of the Bride',
  url: 'https://www.imdb.com/title/tt0101862/'
}
```

For further options/configuration on finding documents, please review [the docs](https://www.mongodb.com/docs/manual/reference/method/db.collection.findOne/).

## Updating documents

Let's say we want to give a film a rating. We can do this via an update.

```shell
db.films.updateOne({ title: "The Big Lebowski" }, { $set: { rating: 5 }})
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
```

The benefit of a NoSQL data store is the fact that documents can have varying fields. Let's checkout what the documents look like now:

```shell
> db.films.find({})
[
  {
    _id: ObjectId("626eaad80dd6e8884b86fda3"),
    title: 'The Big Lebowski',
    url: 'https://en.wikipedia.org/wiki/The_Big_Lebowski',
    rating: 5
  },
  {
    _id: ObjectId("626eaae00dd6e8884b86fda4"),
    title: 'How to loose a guy in 10 days',
    url: 'https://en.wikipedia.org/wiki/How_to_Lose_a_Guy_in_10_Days'
  },
  {
    _id: ObjectId("626eaae00dd6e8884b86fda5"),
    title: 'Father of the Bride',
    url: 'https://www.imdb.com/title/tt0101862/'
  }
]
```

You can see that only one film document has a `rating` field.

For further options/configuration on updating documents, please review [the docs](https://www.mongodb.com/docs/manual/reference/method/db.collection.updateOne/).

## Deleting documents

Deleting documents is very much akin to finding documents. So let's say we want to delete one document:

```shell
> db.films.deleteOne({_id: ObjectId("626eaae00dd6e8884b86fda5")})
{ acknowledged: true, deletedCount: 1 }
```

For further options/configuration on deleting documents, please review [the docs](https://www.mongodb.com/docs/manual/reference/method/db.collection.deleteOne/).

## Configuration file

We can create a configuration file called `~/.mongoshrc.js` to customise the prompt. An example could be:

```js
{
  prompt = () => {
    return `${db.getName()} with ${db.stats().objects} documents> `
  }
}
```

If you save this file, and then reconnect you should see your prompt as:

```shell
entertainment with 2 documents>
```

For further information on the configuration file, please review [the docs](https://www.mongodb.com/docs/mongodb-shell/mongoshrc/).

## Tidbits

- `mongosh` has tab completion, which really helps discoverability of commands. If you run `db.[tab][tab]` you will see a list of commands on the `db` object. Likewise, if you do `db.films.[tab][tab]` you will see a list of commands on the `collections` object.

---

I hope this provides some useful knowledge to get you through your day using MongoDB. It should provide a grounding of basic commands, and provide links to give you further reading for more advanced commands/options.

Photo by [Alfons Morales](https://unsplash.com/@alfonsmc10?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)

---

### See also

- [Git commands to get you through the day](https://benmatselby.dev/post/git-101/)
- [Docker knowledge to get you through the day](https://benmatselby.dev/post/docker-101/)
- [Shell commands to get you through the day](https://benmatselby.dev/post/shell-101/)
- [Terraform knowledge to get you through the day](https://benmatselby.dev/post/terraform-101/)