Mongo shell commands to get you through the day

May 1, 2022 · 6 min read

I recently started a new job. The data store is MongoDB, 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 if there are discrepancies.

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

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:

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:

> 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.

> show dbs

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

> 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:

> 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:

> use entertainment
switched to db entertainment

And then let’s drop the database.

> 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.

> db.getName()
entertainment

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

> db.createCollection("films")

For further options/configuration on creating collections, please review the docs.

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.

> show collections
films

Inserting documents

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

> 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.

> 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.

Getting documents

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

> 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:

> 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:

> 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?

> 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.

Updating documents

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

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:

> 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.

Deleting documents

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

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

For further options/configuration on deleting documents, please review the docs.

Configuration file

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

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

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

entertainment with 2 documents>

For further information on the configuration file, please review the docs.

Tidbits


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.


See also