The MongoDB Book

How to start mongo up in docker and connect to it

// (1) Download a docker image that holds a mongodb database
$ docker pull mongo

// (2) Run a docker container that has the mongo database in it
$ docker run -d -p 27017-27019:27017-27019 --name mongodb mongo

// (3) Connect to the mongo database in the docker container
$ docker exec -it mongodb mongo

How to see what the active database is

> db

How to switch to a new (or existing) database

> use natours-test

How to insert a document into a collection in the active database

// db - the active database
// tours - the collection (Will be created if it does not exist)
// insertOne - the function used to add a single document to the collection
// {a: "ape"} - the document to insert into the collection

> db.tours.insertOne({ a: "ape" })

How to get a list of all the databases that are available

> show dbs

How to see what collections are available in the active database

> show collections

How to see what documents are in a collection

// db - the active database
// tours - the collection
// find - get all documents satisfying query (no query means get all)

> db.tours.find()

How to create an AND query

// Find all documents in the tours collections WHERE 
// the a field has the value of 'ape' AND
// the age field is less than 15

> db.tours.find({ a: {$eq: 'ape' }, age: {$lt: 15} })
> db.tours.find({ $and: [{age: 15 }, { a: 'ape' } ] }) 

How to create an OR query

// Find all documents in the tours collections WHERE 
// the age field has the value of 10 OR 15

> db.tours.find({ $or: [{age: 10 }, { age: 20 } ] })

How to get a projection from your results

// Find all documents in the tours collection
// with a field of a whose value is 'ape' and 
// only return the age field in the results

> db.tours.find({ a: 'ape' }, {age: 1})

How to update a document in a collection

// Find the first document where a='ape' and age=20,
// then update age to 15

> db.tours.updateOne({ a: 'ape', age: 20 }, {$set: { age: 15 }})

How to replace a document in a collection

// Find a document in the tours collection where a='ape' and age=15
// then replace it with a new document where a='ant' and age=2

> db.tours.replaceOne({ a: 'ape', age: 15 }, { a: 'ant', age: 2 })

How to delete a document from a collection

// Delete one document from the tours collection
// that has a field called a with a value of 'ant'

> db.tours.deleteOne({ a: 'ant' })

Last updated