

C:\mongodb\bin>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" }
>

> 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-> 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-> 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-> db.employees.remove({empName:"Sweety"})
> db.employees.find()
{ "_id" : ObjectId("5103cc6d9246bd2515d07374"), "empName" : "Dinesh", "age" : "2
6", "salary" : "70000" }
>
Note:> db.employees.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "dineshonjavaDB.employees",
"name" : "_id_"
}
]
>
To create an index, uses db.tablename.ensureIndex(column). > 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). > 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}). > 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-> 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
>
Labels: mongodb