Install

Installation via homebrew (mac)

brew update
brew install mongodb

Check MongoDB path

// /usr/local/bin/mongod
which mongod

Add the data DB directory to machine

// Might need sudo
mkdir -p /data/db

// If permissions problems
chmod 777 /data/db

 

General

Start mongo Daemon

mongod

// ctrl + c twice to end process

 

Inside the shell

With mongo running, open another terminal to access via the shell. This is an access point to the DB where it can be controlled

mongo

Show the DB’s (only DB’s with data will show)

show dbs

Create new DB

use DBNAME

Add some data (ensure you’re on the right DB, eg use command)

// db - refers to the current local DB
// post - refers to collection of documents
// insert - is a method
db.post.insert({name: 'Shane'})

Show collections

show collections

List documents in collection

db.COLLECTION.find()

// if large you can limit
db.COLLECTION.find().limit(2)

Contents of current directory

ls()

Load a file

load('FILEPATH')

See length of documents in collection

db.COLLECTION.count()

View individual document

db.COLLECTION.count()[0]

 

Managing collections

Get collections of the DB

db.getCollectionNames()

See indexes in collection

db.COLLECTIONNAME.getIndexes()

Create index on Collection (Mongo allocates an ID by default)

// db.COLLECTIONNAME.createIndex(keys, options)
db.COLLECTIONNAME.createIndex({name: 1})

Delete index on collection

db.COLLECTIONNAME.dropIndex('NAME')

Determining what’s returned from collection

// db.COLLECTION.find(QUERY, PROJECTION)

db.COLLECTION.find({}, {name: false, anotherfield: false})
db.COLLECTION.find({}, {name: true})

// return only name
db.COLLECTION.find({name: "NAME"}, {name: true})

// Return whole object
db.COLLECTION.find({name: "NAME"})

db.COLLECTION.find({$0r: [{name: "NAMEONE"}, {name: "NAMETWO"}]})

 

Updating data

Update

db.COLLECTIONNAME.update({NAME: 'Shane'}, {$set: {tags: ['foo'. 'bar']}, title: 'UPDATED'})

See fields for document

Object.keys(db.COLLECTION.find()[0])

Sort results, combination of find and sort

db.COLLECTIONNAME.find({}, {name: true}).sort({name: -1});

Pagination

db.COLLECTIONNAME.find({}, {name: true}).limit(2).skip(2);

// Used in combination with sort
db.COLLECTIONNAME.find({}, {name: true}).limit(2).skip(2).sort({title: -1});

Worthy of Note

Worthy of Note is a site aimed at Web Designers & Developers. It offers a wide range of resources to help assist anyone in the web industry.

View