Installation of MongoDB 3.2 on Ubuntu 14.04

sudo apt-key adv --keyserver hkp:// --recv EA312927
echo "deb trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
sudo apt-get update
sudo apt-get install -y mongodb-org

Some useful commands

# start/stop/restart
sudo service mongod start

# log
cat /var/log/mongodb/mongod.log

# launch MongoDB shell


MongoDB Shell

select a database

use <database>

Note: also used to create a new database.

insert a document into a collection

db.apples.insert({name: "Red Delicious", color: "red"});

list documents in a collection

# all

# limit/offset

# sort desc/asc
db.apples.find().sort({age: -1, name: 1})

# get only some fields (note: _id is always returned, but can be removed using "_id": 0)
db.apples.find({}, {"name": 1})

list documents in a collection (with filters)

# field1 = value1 and field2 = value2
db.apples.find({"field1": "value1", "field2": "value2"})

# field1 >= 10 and field1 <= 100
db.apples.find({"field1": {"$gte": 10, "$lte": 100}})

# field1 in (60, 100, "test")
db.apples.find({"field1": {"$in": [60, 100, "test"]}})

# field1 exist in the document
db.apples.find({"field1": {"$exists": true }})

# field1 contains the string "ed" (case insensitive)
db.apples.find({"field1": /ed/i})

count the number of documents returned by a query


Move database folder

Stop mongodb

sudo service mongod stop

Copy database folder to new location

cp -R /var/lib/mongodb /mnt/volume

Update database folder location in mongod.conf

sudo vi /etc/mongod.conf

# Where and how to store data.
  dbPath: /mnt/volume/mongodb

Start mongodb

sudo service mongod start