In this tutorial we will take first step to write Hello World Example in the MongoDB. Here a quick guide to show you how to do basic operations like create, update, find, delete record and indexing in MongoDB. This example is using MongoDB 2.2.2, running on Window 7 OS 64 bit, both MongoDB client and server console are run on localhost, same machine.
1. Install MongoDB-
Just after downloading the MongoDB zip from its official site and unzip these file and locate to the c:/mongodb/ folder. Open command prompt and change directory to the c:/mongodb/bin/
and run the following command
c:/mongodb/bin>mongod
then you will get the following screen
2. Connect MongoDB-
To connect MongoDB, uses
c:/mongodb/bin>mongo
3. Create a database or table-
In MongoDB, both database and table are created automatically when the first time data is inserted. Uses use database-name, to switch to your database (even this is not created yet).
In below example, after you inserted a single record, database “dineshonjavaDB”, and table “employees” are created on the fly.
C:mongodbbin>mongo MongoDB shell version: 2.2.1 connecting to: test > > use dineshonjavaDB switched to db dineshonjavaDB > db.employees.insert({empName:"Dinesh", age:"26", salary:"50000"}) > db.employees.find() { "_id" : ObjectId("5103cc6d9246bd2515d07374"), "empName" : "Dinesh", "age" : "2 6", "salary" : "50000" } >
Three database commands.
- show dbs – List all databases.
- use db_name – Switches to db_name.
- show collections – List all tables in the current selected database.
NOTE: In MongoDB, collection means table in SQL.
4. Insert A Record-
To insert a record,
uses db.tablename.insert({data})
or db.tablename.save({data})
> db.employees.save({empName:"Sweety", age:"23",salary:"30000"}) > db.employees.find() { "_id" : ObjectId("5103cc6d9246bd2515d07374"), "empName" : "Dinesh", "age" : "2 6", "salary" : "50000" } { "_id" : ObjectId("5103cee89246bd2515d07375"), "empName" : "Sweety", "age" : "2 3", "salary" : "30000" } >
5. Update A Record-
To update a record, uses db.tablename.update({criteria},{$set: {new value}}).
In below example, the salary of empName: “Dinesh” is updated.
> db.employees.update({empName:"Dinesh"},{$set:{salary:"70000"}}) > db.employees.find() { "_id" : ObjectId("5103cc6d9246bd2515d07374"), "empName" : "Dinesh", "age" : "2 6", "salary" : "70000" } { "_id" : ObjectId("5103cee89246bd2515d07375"), "empName" : "Sweety", "age" : "2 3", "salary" : "30000" } >
6. Find Records-
To find or query records, uses db.tablename.find({criteria}).
List all records from table “employees”.
> db.employees.find() { "_id" : ObjectId("5103cc6d9246bd2515d07374"), "empName" : "Dinesh", "age" : "2 6", "salary" : "70000" } { "_id" : ObjectId("5103cee89246bd2515d07375"), "empName" : "Sweety", "age" : "2 3", "salary" : "30000" } >
Find records where employee name is “Dinesh”
> db.employees.find({empName:"Dinesh"}) { "_id" : ObjectId("5103cc6d9246bd2515d07374"), "empName" : "Dinesh", "age" : "2 6", "salary" : "70000" } >
7. Delete Record-
To delete a record, uses db.tablename.remove({criteria}).
In below example, the record of employee name “Sweety” is deleted.
> db.employees.remove({empName:"Sweety"}) > db.employees.find() { "_id" : ObjectId("5103cc6d9246bd2515d07374"), "empName" : "Dinesh", "age" : "2 6", "salary" : "70000" } >
Note:
To delete all records from a table, uses db.tablename.remove().
To drop the table, uses db.tablename.drop().
8. Indexing-
Index may help you increase the speed of querying data.
List all indexes of table “employees”, by default the column “_id” is always the primary key and created automatically.
> db.employees.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "ns" : "dineshonjavaDB.employees", "name" : "_id_" } ] >
To create an index, uses db.tablename.ensureIndex(column).
In below example, an index is created on column “empName”.
> db.employees.ensureIndex({empName:1}) > db.employees.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "ns" : "dineshonjavaDB.employees", "name" : "_id_" }, { "v" : 1, "key" : { "empName" : 1 }, "ns" : "dineshonjavaDB.employees", "name" : "empName_1" } ] >
To drop an index, uses db.tablename.dropIndex(column).
In below example, the index on column “empName” is deleted or dropped.
> db.employees.dropIndex({empName:1}) { "nIndexesWas" : 2, "ok" : 1 } > db.employees.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "ns" : "dineshonjavaDB.employees", "name" : "_id_" } ] >
To create an unique index, uses db.tablename.ensureIndex({column},{unique:true}).
In below example, an unique index is created on column “empName”.
> db.employees.ensureIndex({empName:1},{unique:true}); > db.employees.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "ns" : "dineshonjavaDB.employees", "name" : "_id_" }, { "v" : 1, "key" : { "empName" : 1 }, "unique" : true, "ns" : "dineshonjavaDB.employees", "name" : "empName_1" } ] >
10. Help-
At last, uses help() to guide you how to do things in MongoDB.
help – All available commands.
> help db.help() help on db methods db.mycoll.help() help on collection methods sh.help() sharding helpers rs.help() replica set helpers help admin administrative help help connect connecting to a db help help keys key shortcuts help misc misc things to know help mr mapreduce show dbs show database names show collections show collections in current database show users show users in current database show profile show most recent system.profile entries wit h time >= 1ms show logs show the accessible logger names show log [name] prints out the last segment of log in memor y, 'global' is default use set current database db.foo.find() list objects in collection foo db.foo.find( { a : 1 } ) list objects in foo where a == 1 it result of the last line evaluated; use to f urther iterate DBQuery.shellBatchSize = x set default number of items to display on s hell exit quit the mongo shell >
db.help() – Shows help on db.
> db.help() DB methods: db.addUser(username, password[, readOnly=false]) db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs comma nd [ just calls db.runCommand(...) ] db.auth(username, password) db.cloneDatabase(fromhost) db.commandHelp(name) returns the help for the command db.copyDatabase(fromdb, todb, fromhost) db.createCollection(name, { size : ..., capped : ..., max : ... } ) db.currentOp() displays currently executing operations in the db db.dropDatabase() db.eval(func, args) run code server-side db.fsyncLock() flush data to disk and lock server for backups db.fsyncUnlock() unlocks server following a db.fsyncLock() db.getCollection(cname) same as db['cname'] or db.cname db.getCollectionNames() db.getLastError() - just returns the err msg string db.getLastErrorObj() - return full status object db.getMongo() get the server connection object db.getMongo().setSlaveOk() allow queries on a replication slave server db.getName() db.getPrevError() db.getProfilingLevel() - deprecated db.getProfilingStatus() - returns if profiling is on and slow threshold db.getReplicationInfo() db.getSiblingDB(name) get the db at the same server as this one db.hostInfo() get details about the server's host db.isMaster() check replica primary status db.killOp(opid) kills the current operation in the db db.listCommands() lists all the db commands db.loadServerScripts() loads all the scripts in db.system.js db.logout() db.printCollectionStats() db.printReplicationInfo() db.printShardingStatus() db.printSlaveReplicationInfo() db.removeUser(username) db.repairDatabase() db.resetError() db.runCommand(cmdObj) run a database command. if cmdObj is a string, tu rns it into { cmdObj : 1 } db.serverStatus() db.setProfilingLevel(level,) 0=off 1=slow 2=all db.setVerboseShell(flag) display extra information in shell output db.shutdownServer() db.stats() db.version() current version of the server >
db.collection.help() – Shows help on collection (table).
> db.employees.help() DBCollection help db.employees.find().help() - show DBCursor help db.employees.count() db.employees.copyTo(newColl) - duplicates collection by copying all docu ments to newColl; no indexes are copied. db.employees.convertToCapped(maxBytes) - calls {convertToCapped:'employe es', size:maxBytes}} command db.employees.dataSize() db.employees.distinct( key ) - eg. db.employees.distinct( 'x' ) db.employees.drop() drop the collection db.employees.dropIndex(name) db.employees.dropIndexes() db.employees.ensureIndex(keypattern[,options]) - options is an object wi th these possible fields: name, unique, dropDups db.employees.reIndex() db.employees.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return. e.g. db.employees.find( {x :77} , {name:1, x:1} ) db.employees.find(...).count() db.employees.find(...).limit(n) db.employees.find(...).skip(n) db.employees.find(...).sort(...) db.employees.findOne([query]) db.employees.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } ) db.employees.getDB() get DB object associated with collection db.employees.getIndexes() db.employees.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) db.employees.insert(obj) db.employees.mapReduce( mapFunction , reduceFunction , ) db.employees.remove(query) db.employees.renameCollection( newName , ) renames the coll ection. db.employees.runCommand( name , ) runs a db command with the g iven name where the first param is the collection name db.employees.save(obj) db.employees.stats() db.employees.storageSize() - includes free space allocated to this colle ction db.employees.totalIndexSize() - size in bytes of all the indexes db.employees.totalSize() - storage allocated for all data and indexes db.employees.update(query, object[, upsert_bool, multi_bool]) - instead of two flags, you can pass an object with fields: upsert, multi db.employees.validate( ) - SLOW db.employees.getShardVersion() - only for use with sharding db.employees.getShardDistribution() - prints statistics about data distr ibution in the cluster db.employees.getSplitKeysForChunks( ) - calculates split points over all chunks and returns splitter function >
db.collection.function.help() – Shows help on function.
> db.employees.find().help() find() modifiers .sort( {...} ) .limit( n ) .skip( n ) .count() - total # of objects matching query, ignores skip,limit .size() - total # of objects cursor would return, honors skip,limit .explain([verbose]) .hint(...) .addOption(n) - adds op_query options -- see wire protocol ._addSpecial(name, value) - http://dochub.mongodb.org/core/advancedqueri es#AdvancedQueries-Metaqueryoperators .batchSize(n) - sets the number of docs to return per getMore .showDiskLoc() - adds a $diskLoc field to each returned object .min(idxDoc) .max(idxDoc) Cursor methods .toArray() - iterates through docs and returns an array of the results .forEach( func ) .map( func ) .hasNext() .next() .objsLeftInBatch() - returns count of docs left in current batch (when e xhausted, a new getMore will be issued) .count(applySkipLimit) - runs command at server .itcount() - iterates through documents and counts them >
References