Contents

MongoDB on the Command Line

We are using authentication for our MongoDB instance. As such, you need to enter credentials. The general format is this (replace [your username] with your username and [your database] with the database ):

mongo localhost/[your database] -u [your username] -p

Then enter your password. Once in, you can select your database. I have databases created for each student and group. The study databases are in the format db_USERNAME and the team databases are in the form team_LASTNAME, where LASTNAME corresponds to the last name of the alphabetically first team member.

To select a database, do the following:

use [name of database]

where [name of database] is the name of the database you want to use. You can reference collections in the current database by doing:

db.[name of collection].[name of function](...)

where [name of collection] is the name of the collection you want to use and [name of function] is the name of a MongoDB function you want to invoke. A collection does not have to exist for you to use it.

Examples

The following will insert a simple document into a collection called users in the database db_example_user:

use db_example_user
db.users.insert({
  username: "foobar",
  hasPets: false
})

You can search for the documents currently in the collection with this:

db.users.find()

You can search for all documents with a given username by doing:

db.users.find({ username: "foobar" })

Other MongoDB commands

There are a bunch of useful commands you can issue in the MongoDB shell. For a list of these and examples of how to use them, see this MongoDB shell cheat sheet.