MongoDB Tutorial

DISCLAIMER: Please consult all commands bellow with official documentation for more complete understanding.

Run mongo shell. You have to have CIRC account.

# Connect to bluehive
$ ssh <netid>@bluehive.circ.rochester.edu

# Run interactive mode on bluehive
$ interactive -p standard -t 2:00:00

# Load mongo module
$ module load mongodb/3.4.10

# Run mongo daemon
# Replace XX with your classID
mongod --dbpath mongo --port 270XX > mongod.log &

# Run mongo console
$ mongo --port 270XX 
# Run mongo console with databse ebay
$ mongo --port 270XX ebay 

Now we are in the mongo console and we can execute commands. Here we will present basic command ($) examples introduced with a comment (#):

Database

# Display help
$ help

# Create a new database called <netid>
$ use <netid>

# List existing databases
$ show dbs

Collections

# Create new collections called actors and movies
$ db.createCollection("actors")
$ db.createCollection("movies")

# List existing collections
$ show collections
$ db.getCollectionNames()

Insertion

# Insert new document
$ db.actors.insert({name : "Arnold Schwarzenegger"})

# Insert new document with given _id (~ primary key)
$ db.actors.insert({_id : 2, name : "Arnold Schwarzenegger"})
# .save is a wrapper for .insert and .update together
$ db.actors.save({name : "Arnold Schwarzenegger"})
$ db.actors.save({_id : ObjectId(), name : "Arnold Schwarzenegger"})

# Retrieve available documents
$ db.actors.find()

Update

# Updating existing documents
$ db.actors.update({name : "Arnold Schwarzenegger"}, {$set : {yearOfBirth : 1961})
$ db.actors.save({_id : 2}, {$set : {yearOfBirth : 1973}})
$ db.actors.update({_id : 2}, {$set : {_id : ObjectId()}}

Removals

# Remove an existing document
$ db.actors.remove({_id : 2})

# Insert new documents
$ db.actors.update({name : "Arnold Schwarzenegger"}, {$set : {yearOfBirth : 1973}}, {upsert : true})
$ db.movies.save({title : "Terminator"})

References

# Link actors and movies
$ db.actors.update({name : "Arnold Schwarzenegger"}, {$push : {movies : "Terminator"}})
$ db.actors.update({name : "Arnold Schwarzenegger"}, {$set : {"movies.0" : ObjectId("<id_of_our_movie>")}}

Querying

# Retrieve relevant documents
# Actors with specified movies
$ db.actors.find({movies : {$exists : true}})

# Actors that have year of birth greater than 1960
$ db.actors.find({yearOfBirth : {$gt : 1960}})

# All actors projected to their names only
$ db.actors.find({}, {name : 1, _id : 0)

# All actors sorted using their names in a descending order
$ db.actors.find().sort({name : -1})

# The first two actors according to their names
$ db.actors.find().sort({name : 1}).limit(2)

Indices

# Explore evaluation plans
$ db.actors.find({movies : ObjectId("2")}).explain()

# Create a new index
$ db.actors.createIndex({movies : 1})
Acknowledgement: First draft produced by Vojtech Aschenbrenner