<p>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.</p>
<h2><b>1. Install MongoDB-</b></h2>
<p>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/<br />
and run the following command</p>
<p><b>c:/mongodb/bin>;mongod</b></p>
<p>then you will get the following screen<br />
<img class="aligncenter" src="https://dineshonjava.com/wp-content/uploads/2013/01/mongodbcmd.png" border="0" /></p>
<h2><b>2. Connect MongoDB-</b></h2>
<p>To connect MongoDB, uses</p>
<p><b>c:/mongodb/bin>;mongo</b></p>
<div class="separator" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em; text-align: center;"><img class="aligncenter" src="https://dineshonjava.com/wp-content/uploads/2013/01/mongo.png" width="400" height="127" border="0" /></div>
<h2><b>3. Create a database or table-</b></h2>
<p>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).</p>
<p>In below example, after you inserted a single record, database &#8220;dineshonjavaDB&#8221;, and table &#8220;employees&#8221; are created on the fly.</p>
<pre class="highlight">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" } 
>; 
</pre>
<p><img src="https://dineshonjava.com/wp-content/uploads/2013/01/heelo.png" width="600" height="233" border="0" /><br />
Three database commands.</p>
<ol>
<li><b>show dbs</b> – List all databases.</li>
<li><b>use db_name </b>– Switches to db_name.</li>
<li><b>show collections</b> – List all tables in the current selected database.</li>
</ol>
<p><b>NOTE: </b>In <b>MongoDB</b>, <b>collection</b> means <b>table</b> in SQL.</p>
<h2><b>4. Insert A Record-</b></h2>
<p>To insert a record,<br />
uses db.tablename.insert({data})<br />
or db.tablename.save({data})</p>
<pre class="highlight">>; 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" } 
>; 
</pre>
<h2><b>5. Update A Record-</b></h2>
<p>To update a record, uses <b>db.tablename.update({criteria},{$set: {new value}})</b>.<br />
In below example, the salary of empName: &#8220;Dinesh&#8221; is updated.</p>
<pre class="highlight">>; 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" } 
>; 
</pre>
<h2><b>6. Find Records-</b></h2>
<p>To find or query records, uses <b>db.tablename.find({criteria}).<br />
</b><br />
List all records from table &#8220;employees&#8221;.</p>
<pre class="highlight">>; db.employees.find() 
{ "_id" : ObjectId("5103cc6d9246bd2515d07374"), "empName" : "Dinesh", "age" : "2 
6", "salary" : "70000" } 
{ "_id" : ObjectId("5103cee89246bd2515d07375"), "empName" : "Sweety", "age" : "2 
3", "salary" : "30000" } 
>; 
</pre>
<p>Find records where employee name is &#8220;Dinesh&#8221;</p>
<pre class="highlight">>; db.employees.find({empName:"Dinesh"}) 
{ "_id" : ObjectId("5103cc6d9246bd2515d07374"), "empName" : "Dinesh", "age" : "2 
6", "salary" : "70000" } 
>; 
</pre>
<h2><b>7. Delete Record-</b></h2>
<p>To delete a record, uses <b>db.tablename.remove({criteria})</b>.<br />
In below example, the record of employee name &#8220;Sweety&#8221; is deleted.</p>
<pre class="highlight">>; db.employees.remove({empName:"Sweety"}) 
>; db.employees.find() 
{ "_id" : ObjectId("5103cc6d9246bd2515d07374"), "empName" : "Dinesh", "age" : "2 
6", "salary" : "70000" } 
>; 
</pre>
<p><b>Note:</b><br />
To delete all records from a table, uses <b>db.tablename.remove()</b>.<br />
To drop the table, uses <b>db.tablename.drop()</b>.</p>
<h2><b>8. Indexing-</b></h2>
<p>Index may help you increase the speed of querying data.</p>
<p>List all indexes of table &#8220;employees&#8221;, by default the column &#8220;_id&#8221; is always the primary key and created automatically.</p>
<pre class="highlight">>; db.employees.getIndexes() 
[ 
 { 
 "v" : 1, 
 "key" : { 
 "_id" : 1 
 }, 
 "ns" : "dineshonjavaDB.employees", 
 "name" : "_id_" 
 } 
] 
>; 
</pre>
<p>To create an index, uses <b>db.tablename.ensureIndex(column)</b>.<br />
In below example, an index is created on column &#8220;empName&#8221;.</p>
<pre class="highlight">>; 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" 
 } 
] 
>; 
</pre>
<p>To drop an index, uses <b>db.tablename.dropIndex(column)</b>.<br />
In below example, the index on column &#8220;empName&#8221; is deleted or dropped.</p>
<pre class="highlight">>; db.employees.dropIndex({empName:1}) 
{ "nIndexesWas" : 2, "ok" : 1 } 
>; db.employees.getIndexes() 
[ 
 { 
 "v" : 1, 
 "key" : { 
 "_id" : 1 
 }, 
 "ns" : "dineshonjavaDB.employees", 
 "name" : "_id_" 
 } 
] 
>; 
</pre>
<p>To create an unique index, uses <b>db.tablename.ensureIndex({column},{unique:true})</b>.<br />
In below example, an unique index is created on column &#8220;empName&#8221;.</p>
<pre class="highlight">>; 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" 
 } 
] 
>; 
</pre>
<h2>10. Help-</h2>
<p>At last, uses help() to guide you how to do things in MongoDB.<br />
<b>help –</b> All available commands.</p>
<pre class="highlight">>; 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 
>; 
</pre>
<p><b>db.help() </b>– Shows help on db.</p>
<pre class="highlight">>; 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 
>; 
</pre>
<p><b>db.collection.help()</b> – Shows help on collection (table).</p>
<pre class="highlight">>; 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 
>; 
</pre>
<p><b> db.collection.function.help()</b> – Shows help on function.</p>
<pre class="highlight">>; 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 
>; 
</pre>
<p> ;</p>
<h4>References</h4>
<ol>
<li><a href="http://www.mongodb.org/display/DOCS/Tutorial" target="_blank" rel="noopener">Official MongoDB tutorials<br />
</a></li>
<li><a href="http://www.mongodb.org/display/DOCS/Indexes" target="_blank" rel="noopener">MongoDB Indexes</a></li>
</ol>
<div style="background-color: #ff99cc;"> <b> <;<;<a href="https://dineshonjava.com/install-mongodb-on-windows/">previous</a><;<; || <a href="https://dineshonjava.com/introduction-to-mongodb/">index </a>|| >;>;<a href="https://dineshonjava.com/create-database-or-collection-in-mongodb/">next</a>>;>;</b></div>
<p> ;</p>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/install-mongodb-on-windows/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/create-database-or-collection-in-mongodb/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '595'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…