====== Introduction ====== From [[http://www.mongodb.org/|the hp]]: "MongoDB (from "humongous") is a scalable, high-performance, open source NoSQL database. Written in C++, features" * Document-Oriented Storage (JSON-style documents with dynamic schemas offer simplicity and power) * Full Index Support (Index on any attribute) * Replication & High Availability (Mirror across LANs and WANs) * Auto-Sharding (Scale horizontally without compromising functionality) * Querying * Fast In-Place Updates * Map/Reduce * GridFS * Commercial Support This page aims to be a MongoDB **"hello world"** example, for more info read * [[MongoDBCookBook]] * [[MongoDBAdmin]] ===== Differences to traditional DBMS ===== MongoDB does not support transactions. [[http://www.mongodb.org/display/DOCS/Atomic+Operations|Atomic operations]] are supported. ====== Getting started ====== sudo apt-get install mongodb will pull in all dependencies, install and start the database. If required, adjust settings in /etc/mongodb.conf (like IP binding or port) ===== Start/stop database ===== sudo service mongodb stop sudo service mongodb start ===== Login to database ===== An easy way is the [[http://www.mongodb.org/display/DOCS/mongo+-+The+Interactive+Shell|mongo]] interactive shell. In a terminal, type mongo This connects to database "test". ====== Usage examples ====== The information below comes from the [[http://www.mongodb.org/display/DOCS/Manual|MongoDB manual]] ===== Use a specific database ===== To use a specific database, say "accounts", login to mongo and issue >use accounts If database "accounts" does not exist yet, it will be created. List all existing databases: >show dbs ===== Collections ===== MongoDB [[http://www.mongodb.org/display/DOCS/Collections|collections]] can be compared to RDBS tables. Collections are named groupings of documents. Login to a specific database and list existing collections: >use accounts >show collections As with databases, the first time you access a collection, it will be automatically be created for you. ===== Insert documents ===== As mentioned before, MongoDB is document-oriented. Whereas you think of //rows// in RDBMS, you think of [[http://www.mongodb.org/display/DOCS/Documents|documents]] in MongoDB. More specifically, MongoDB documents are in JSON format. Insert one document > db.transactions.save({"name":"alice","type":"withdrawal", "amount": 30}) or bulk insert (supported in shell since v2.2) >db.transactions.save([{"name":"alice","type":"deposit", "amount": 500}, {"name":"alice","type":"withdrawal", "amount": 50}, {"name":"bob","type":"withdrawal", "amount": 20}, {"name":"bob","type":"withdrawal", "amount": 60}]) ===== Update ===== Change transaction type to "deposit" where name=bob and amount 60 > db.transactions.update({"name":"bob", "amount":60}, {$set : {"type":"deposit"}}) ===== Delete documents ===== db.transactions.drop() //drop the entire transactions collection db.transactions.remove() //remove all objects from the collection db.transactions.remove( { name : "sara" } ) //remove objects from the collection where name is sara ===== Retrieve data ===== Get all documents > db.transactions.find() ==== With WHERE clause==== Alice's money transactions: > db.transactions.find({"name" : "alice"}) ==== Only specific fields ==== Show only type and amount fields > db.transactions.find({}, {"type":true, "amount":true, "_id":false}) ==== Limit result to x rows ==== > db.transactions.find({}, {}).limit(2) ==== Sort results ==== sort by name ascending, amount descending > db.transactions.find( {},{}).sort({"name":1,"amount":-1}) ==== Indizes ==== Run ensureIndex(), which builds the index ONLY if it does not already exist. db.transactions.ensureIndex({"name":true}); View existing indizes db.transactions.getIndexes() The [[http://docs.mongodb.org/manual/core/indexes/|manual]] has more details. ===== Simple analyses ===== ==== Count lines ==== > db.transactions.count() // or with a WHERE clause > db.transactions.count({"name":"alice"}) ==== Calculate sum ==== How much did all users withdraw? > db.transactions.group( { "key": {"name":true} , "cond": {"type":"withdrawal"}, "reduce": function (obj,prev) { prev.csum += obj.amount; }, "initial": { csum: 0 } } ) ==== Calculate average ==== ==== Distinct values ==== > db.transactions.distinct("name") ==== Analyse query ==== Use [[http://www.mongodb.org/display/DOCS/Explain#Explain-millis|explain()]] to get statistics about a query, e.g. check "millis" for the query runtime in milliseconds. **NOTE: during the execution of explain(), the actual query is being run!** So if the query takes lots of time, explain() will take a long time, too. > db.transactions.find({},{"name":true, "amount":"true"}).explain() { "cursor" : "BasicCursor", "isMultiKey" : false, "n" : 6, "nscannedObjects" : 6, "nscanned" : 6, "nscannedObjectsAllPlans" : 6, "nscannedAllPlans" : 6, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 0, "indexBounds" : { }, "server" : "ankh:27017" }