Wednesday 9 October 2013

Hello World Example Using Mongo Client Console on MongoDB

Posted by Kanhaiya

In this tutorial we'll take first step to write Hello World Example in the MongoDB. It'll show you how to do basic operations like create, update, find and delete record in MongoDB. These operations are performs using MongoDB client console and server console 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 by uses this command

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 "testJavaDb", and table "users" are created on the fly.
C:\mongodb\bin>mongo
MongoDB shell version: 2.4.6
connecting to: test
> use testJavaDb
switched to db testJavaDb
> db.users.insert({firstName:"Kanhaiya", lastName:"Sahu", age:"26", companyName:
"TBSL"});
> db.users.find();
{ "_id" : ObjectId("52544875cb1f732ae68c79b5"), "firstName" : "Kanhaiya", "lastN
ame" : "Sahu", "age" : "26", "companyName" : "TBSL" }
>


Note: In MongoDB, collection means table in SQL.

Three database commands.
  1. show dbs – List all databases.
  2. use db_name – Switches to db_name.
  3. show collections – List all tables in the current selected database.

4. Insert A Record:-
To insert a record,
uses db.tablename.insert({data})
or db.tablename.save({data})
> db.users.save({firstName:"Cuty", lastName:"Pie", age:"22", companyName:"TBSL"}
);
> db.users.find();
{ "_id" : ObjectId("52544875cb1f732ae68c79b5"), "firstName" : "Kanhaiya", "lastN
ame" : "Sahu", "age" : "26", "companyName" : "TBSL" }
{ "_id" : ObjectId("5254510bcb1f732ae68c79b6"), "firstName" : "Cuty", "lastName"
 : "Pie", "age" : "22", "companyName" : "TBSL" }
>

5. Update A Record:-
To update a record, uses db.tablename.update({criteria},{$set: {new value}}).
In below example, the companyName of firstName: "Kanhaiya" is updated.
> db.users.update({firstName:"Cuty"},{$set:{companyName:"HCL"}})
> db.users.find();
{ "_id" : ObjectId("52544875cb1f732ae68c79b5"), "firstName" : "Kanhaiya", "lastN
ame" : "Sahu", "age" : "26", "companyName" : "TBSL" }
{ "_id" : ObjectId("5254510bcb1f732ae68c79b6"), "age" : "22", "companyName" : "H
CL", "firstName" : "Cuty", "lastName" : "Pie" }
>

6. Find Records:-
To find or query records, uses db.tablename.find({criteria}).

List all records from table "users".
> db.users.find();
{ "_id" : ObjectId("52544875cb1f732ae68c79b5"), "firstName" : "Kanhaiya", "lastN
ame" : "Sahu", "age" : "26", "companyName" : "TBSL" }
{ "_id" : ObjectId("5254510bcb1f732ae68c79b6"), "age" : "22", "companyName" : "H
CL", "firstName" : "Cuty", "lastName" : "Pie" }
>

7. Delete Record:-
To delete a record, uses db.tablename.remove({criteria}).
In below example, the record of firstName "Kanhaiya" is deleted.
> db.users.remove({firstName:"Kanhaiya"});
> db.users.find();
{ "_id" : ObjectId("5254510bcb1f732ae68c79b6"), "age" : "22", "companyName" : "H
CL", "firstName" : "Cuty", "lastName" : "Pie" }
>

Note:
To delete all records from a table, uses db.tablename.remove().
To drop the table, uses db.tablename.drop().

8. Help command in mongoDB:-
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
>

9. Help on db methods:-
db.help() – Shows help on db.
> db.help();
DB methods:
        db.addUser(userDocument)
        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
>


10. Help on collection (table name):-
db.collection.help() – Shows help on collection (table). you can replace collection with your table name for showing help
> db.collection.help();
DBCollection help
        db.collection.find().help() - show DBCursor help
        db.collection.count()
        db.collection.copyTo(newColl) - duplicates collection by copying all doc
uments to newColl; no indexes are copied.
        db.collection.convertToCapped(maxBytes) - calls {convertToCapped:'collec
tion', size:maxBytes}} command
        db.collection.dataSize()
        db.collection.distinct( key ) - e.g. db.collection.distinct( 'x' )
        db.collection.drop() drop the collection
        db.collection.dropIndex(index) - e.g. db.collection.dropIndex( "indexNam
e" ) or db.collection.dropIndex( { "indexKey" : 1 } )
        db.collection.dropIndexes()
        db.collection.ensureIndex(keypattern[,options]) - options is an object w
ith these possible fields: name, unique, dropDups
        db.collection.reIndex()
        db.collection.find([query],[fields]) - query is an optional query filter
. fields is optional set of fields to return.
                                                      e.g. db.collection.find( {
x:77} , {name:1, x:1} )
        db.collection.find(...).count()
        db.collection.find(...).limit(n)
        db.collection.find(...).skip(n)
        db.collection.find(...).sort(...)
        db.collection.findOne([query])
        db.collection.findAndModify( { update : ... , remove : bool [, query: {}
, sort: {}, 'new': false] } )
        db.collection.getDB() get DB object associated with collection
        db.collection.getIndexes()
        db.collection.group( { key : ..., initial: ..., reduce : ...[, cond: ...
] } )
        db.collection.insert(obj)
        db.collection.mapReduce( mapFunction , reduceFunction ,  )
        db.collection.remove(query)
        db.collection.renameCollection( newName ,  ) renames the col
lection.
        db.collection.runCommand( name ,  ) runs a db command with the
given name where the first param is the collection name
        db.collection.save(obj)
        db.collection.stats()
        db.collection.storageSize() - includes free space allocated to this coll
ection
        db.collection.totalIndexSize() - size in bytes of all the indexes
        db.collection.totalSize() - storage allocated for all data and indexes
        db.collection.update(query, object[, upsert_bool, multi_bool]) - instead
 of two flags, you can pass an object with fields: upsert, multi
        db.collection.validate(  ) - SLOW
        db.collection.getShardVersion() - only for use with sharding
        db.collection.getShardDistribution() - prints statistics about data dist
ribution in the cluster
        db.collection.getSplitKeysForChunks(  ) - calculates split
 points over all chunks and returns splitter function
>


No comments:

Post a Comment