MongoDB is a document database that provides high performance, high availability and easy scalability. This post is a simple crash course about how to install MongoDB, start it using the default configuration and some basic DBA commands. If you need a complex setup with clusters, ha, sharding, replicas ... this is not the place to be.
Install
[cc lang='bash']
# http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/
\$ apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv
7F0CEB10
\$ echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart
dist 10gen' | tee /etc/apt/sources.list.d/mongodb.list
\$ apt-get update
\$ apt-get install mongodb-org -y
\$ vi /etc/mongod.conf # update configuration if needed
\$ service mongod restart
# data - /var/lib/mongodb/
# logs - /var/log/mongodb/mongod.log
[/cc]
DBA
[cc lang='bash']
\$ mongo --host 127.0.0.1 --port 27017 # connects automatically to the
"test" db if no db is provided
MongoDB shell version: 2.6.3
connecting to: 127.0.0.1:27017/test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
> db # get current db
test
> show dbs # get dbs
admin (empty)
local 0.078GB
> use my-db # create and select "my-db" db
switched to db my-db
> a = { name: "test string" } # create the "a" document (row)
> b = { x : 10 } # create the "b" document (row)
> db.data.insert(a) # insert the "a" document into "data" collection
(table)
WriteResult({ "nInserted" : 1 })
> db.data.insert(b) # insert the "b" document into "data" collection
(table)
WriteResult({ "nInserted" : 1 })
> show collections # list all collections (tables) from "my-db" db
data
system.indexes
> db.data.find() # list all documents from "data" collection
{ "_id" : ObjectId("53de0de6c1332623cc5635d5"), "name" : "test string"
}
> db.data.find().limit(1) # list only the first document from "data"
collection
> db.data.find( { x : 10 } ) # find a specific document in the "data"
collection
> db.data.remove({}) # remove all documents from "data" collection
(indexes will not be removed)
WriteResult({ "nRemoved" : 2 })
> db.data.drop() # remove indexes also
TRUE
> db.dropDatabase() # drop current database
> db # we're still using "my-db" db, but now it's empty
my-db
> show collections # no collections
> show dbs # "my-db" shows empty
admin (empty)
local 0.078GB
my-db (empty)
[/cc]