Categories
mongoDB

MongoDB Notes – Some basic Stuff

This is not a mongoDB Tutorial. Its some of my notes, derived from taking the M101 mongoDB for developers class by 10gen Education. Trying to keep it as compact as possible. So this is not the place to learn mongoDB. At least one person finds this useful.

OS Shell:

Importing from a json export.

mongoimport -d blog -c posts --drop < posts.json

-d sets the db
-c sets the collection

Running mongo shell with a script.

mongo --shell shop doSomething.js

loads the script in the “shop” database context.

Monitoring your instances:

There are some pretty cool utilities that come with Mongo for monitoring your instances.
mongotop – shows how much time was spend reading or writing each collection over the last second
mongostat – brilliant live debug tool, gives a view on all your connected MongoDB instances
MongoDB Monitoring Service – 10gen’s hosted mongo monitoring service. Good starting point.

GUI management Tools:

Robomongo – Shell-centric MongoDB management tool

mongoDB shell, usefull commands:

show dbs              //shows the databases
use dbname            //select a database or create if not exists
show collections      //shows the collections in the selected database
db                    //shows the db in use
db.dropDatabase()     //delete the db is use
db.foo.help()         //help on collection methods
db.currentOp()        //shows all currently running operations
db.killOp(opid)       //kill long running queries
db.serverStatus()     //shows stats for the entire server, very useful for monitoring
db.stats()            //shows you stats for the selected db
db.collection.stats() //stats for the specified collection
db.listCommands()     //list all available commands
db.runCommand({serverStatus :1})     //run commands in the mongo shell

mongoDB Shell, basic commands for CRUD operations:

db.createCollection("foo")     //create a collection named foo
db.foo.find()                  //list all documents in collection foo
db.foo.save({a: 1})            //updates an existing document or inserts a new document depending on the _id field of the document. Performs an insert if the document to save does not contain the _id field.
db.foo.update({a: 1}, {a: 2})  //update document where a == 1 and set a = 2
db.foo.find({a: 1})            //list documents in foo where a == 1
db.foo.insert({a:3,b:5})       //inserts a document in collection foo, throws an error if a document with the same _id already exists
db.foo.find({}, {a:1,b:1})     //list all documents in foo but display only _id,a,b fields
db.foo.remove()                //removes all documents from foo

Hopefully I’ll find the time to post more advanced stuff!