<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>MongoDB &#8211; Sibeesh Passion</title>
	<atom:link href="https://mail.sibeeshpassion.com/tag/mongodb/feed/" rel="self" type="application/rss+xml" />
	<link>https://mail.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Tue, 10 Jul 2018 07:38:45 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>MongoDB &#8211; Sibeesh Passion</title>
	<link>https://mail.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Continue With Learning Indexes in MongoDB</title>
		<link>https://mail.sibeeshpassion.com/continue-with-learning-indexes-in-mongodb/</link>
					<comments>https://mail.sibeeshpassion.com/continue-with-learning-indexes-in-mongodb/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Wed, 07 Mar 2018 16:02:02 +0000</pubDate>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Indexes in MongoDB]]></category>
		<category><![CDATA[Mongo Commands]]></category>
		<category><![CDATA[Mongo Shells]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12673</guid>

					<description><![CDATA[[toc] Introduction This is the third article of the series &#8220;Learn MongoDB with me&#8221;, if you haven&#8217;t read my previous post on this topic, I strongly recommend you to find it here. This is the continuation of exploring the Indexes on MongoDB, we will be discussing about various MongoDB indexes which we can perform on our data. I hope you will find this post useful. Thanks for reading. Learn MongoDB with me You can see all the articles on this series below. Learn MongoDB with me Learn MongoDB with me &#8211; Part 2 Using MongoDB on Node JS Application Using [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>This is the third article of the series &#8220;Learn MongoDB with me&#8221;, if you haven&#8217;t read my previous post on this topic, I strongly recommend you to find it <a href="http://sibeeshpassion.com/category/mongodb/">here</a>. This is the continuation of exploring the Indexes on MongoDB, we will be discussing about various MongoDB indexes which we can perform on our data. I hope you will find this post useful. Thanks for reading.</p>
<h2>Learn MongoDB with me</h2>
<p>You can see all the articles on this series below.</p>
<ul>
<li><a href="http://sibeeshpassion.com/learn-mongodb-with-me/">Learn MongoDB with me</a></li>
<li><a href="http://sibeeshpassion.com/learn-mongodb-with-me-part-2/">Learn MongoDB with me &#8211; Part 2</a></li>
<li><a href="http://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/">Using MongoDB on Node JS Application Using Mongoose</a></li>
</ul>
<h2>Background</h2>
<p>Like I said, it is going to be the third  part of the series. I believe that you have enough knowledge about Mongo DB now,  If not, please consider reading my <a href="http://sibeeshpassion.com/category/mongodb/">previous posts</a> again.</p>
<h2>Indexes in MongoDB</h2>
<p>Let&#8217;s import a new collection, <em>p</em><em>roducts</em> first.<em> </em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">[
   {
      "id":2,
      "name":"An ice sculpture",
      "price":12.50,
      "tags":[
         "cold",
         "ice"
      ],
      "dimensions":{
         "length":7.0,
         "width":12.0,
         "height":9.5
      },
      "warehouseLocation":{
         "latitude":-78.75,
         "longitude":20.4
      }
   },
   {
      "id":3,
      "name":"A blue mouse",
      "price":25.50,
      "dimensions":{
         "length":3.1,
         "width":1.0,
         "height":1.0
      },
      "warehouseLocation":{
         "latitude":54.4,
         "longitude":-32.7
      }
   },
   {
      "id":4,
      "name":"Keyboard",
      "price":15.50,
      "dimensions":{
         "length":1.1,
         "width":1.0,
         "height":1.0
      },
      "warehouseLocation":{
         "latitude":24.4,
         "longitude":-42.7
      }
   },
   {
      "id":5,
      "name":"Doll",
      "price":10.50,
      "dimensions":{
         "length":5.1,
         "width":1.0,
         "height":7.0
      },
      "warehouseLocation":{
         "latitude":64.4,
         "longitude":-82.7
      }
   },
   {
      "id":6,
      "name":"Wallet",
      "price":5.50,
      "dimensions":{
         "length":1.1,
         "width":1.0,
         "height":1.0
      },
      "warehouseLocation":{
         "latitude":24.4,
         "longitude":-12.7
      }
   }
]</pre>
<p>Please be noted that these are just dummy data, and it may sound illogical to you.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">C:\Program Files\MongoDB\Server\3.4\bin&gt;mongoimport --db mylearning --collection products --jsonArray --file products.json
2018-03-06T16:48:34.440+0530    connected to: localhost
2018-03-06T16:48:34.607+0530    imported 5 documents

C:\Program Files\MongoDB\Server\3.4\bin&gt;</pre>
<p>If you don&#8217;t know how the import command works, please read my previous posts where we have seen simple indexes.  Now we have the data, let&#8217;s go perform Indexes.</p>
<h3>Single Key Indexes</h3>
<p>In one of my previous post in this series of article, I had mentioned about simple indexes. Here in this article, we are not going to talk about it, instead  we will explore on other indexing option what MongoDB has. Sounds good? If yes, let&#8217;s continue. let&#8217;s go and see Multi key indexes</p>
<h3>Multi Key Indexes or Compound Indexes</h3>
<p>As the name implies, we are actually going to set indexes with more than one key element. On our products collection, we have some product documents right, what we a user needs to filter the same with the price and warehouse location. Yeah, we need to build a query.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.products.find({
... "price: {$lte: 16},
2018-03-06T17:10:15.005+0530 E QUERY    [thread1] SyntaxError: unterminated string literal @(shell):2:0
MongoDB Enterprise &gt; db.products.find({
... "price": {$lte: 16},
... "warehouseLocation.latitude": {$gte: 60}
... })
{ "_id" : ObjectId("5a9e790a1ae1f955c1a70c4a"), "id" : 5, "name" : "Doll", "price" : 10.5, "dimensions" : { "length" : 5.1, "width" : 1, "height" : 7 }, "warehouseLocation" : { "latitude" : 64.4, "longitude" : -82.7 } }
MongoDB Enterprise &gt;</pre>
<p>We have got one entry according to  our search, <em>&#8220;price&#8221;: {$lte: 16}</em> and <em>&#8220;warehouseLocation.latitude&#8221;: {$gte: 60} </em>that&#8217;s cool. Now let&#8217;s try to find out the execution status for the same.</p>
<p>Please be noted that we have used <em>$lte</em> and <em>$gte</em> which stands for &#8220;less than or equal to&#8221; and &#8220;greater than or equal to&#8221;, remember what I have told you before, &#8220;Mongo shell is cool and we can do anything with it&#8221;. Let&#8217;s find out the examined elements count for our preceding find query now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">db.products.find({ "price": {$lte: 16}, "warehouseLocation.latitude": {$gte: 60} }).explain("executionStats")</pre>
<p>And if your query if correct, you will be getting a result as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">"queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "mylearning.products",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "$and" : [
                                {
                                        "price" : {
                                                "$lte" : 16
                                        }
                                },
                                {
                                        "warehouseLocation.latitude" : {
                                                "$gte" : 60
                                        }
                                }
                        ]
                },
                "winningPlan" : {
                        "stage" : "COLLSCAN",
                        "filter" : {
                                "$and" : [
                                        {
                                                "price" : {
                                                        "$lte" : 16
                                                }
                                        },
                                        {
                                                "warehouseLocation.latitude" : {
                                                        "$gte" : 60
                                                }
                                        }
                                ]
                        },
                        "direction" : "forward"
                },
                "rejectedPlans" : [ ]
        },
        "executionStats" : {
                "executionSuccess" : true,
                "nReturned" : 1,
                "executionTimeMillis" : 107,
                "totalKeysExamined" : 0,
                "totalDocsExamined" : 5,
                "executionStages" : {
                        "stage" : "COLLSCAN",
                        "filter" : {
                                "$and" : [
                                        {
                                                "price" : {
                                                        "$lte" : 16
                                                }
                                        },
                                        {
                                                "warehouseLocation.latitude" : {
                                                        "$gte" : 60
                                                }
                                        }
                                ]
                        },
                        "nReturned" : 1,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 7,
                        "advanced" : 1,
                        "needTime" : 5,
                        "needYield" : 0,
                        "saveState" : 0,
                        "restoreState" : 0,
                        "isEOF" : 1,
                        "invalidates" : 0,
                        "direction" : "forward",
                        "docsExamined" : 5
                }
        },
        "serverInfo" : {
                "host" : "PC292716",
                "port" : 27017,
                "version" : "3.4.9",
                "gitVersion" : "876ebee8c7dd0e2d992f36a848ff4dc50ee6603e"
        },
        "ok" : 1
}</pre>
<p>You might have already noticed the value we have for <em>totalDocsExamined</em> , if you haven&#8217;t please check now. In my case it is 5, which means the query just examined all the records we have. Ah, that sounds bad right? What if we have millions of records on our collection, how long it is gonna take to fetch the results?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.products.createIndex({price:1, "warehouseLocation.latitude":1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}</pre>
<p>Run your previous query now, and find out what is the value of docs examined.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.products.find({ "price": {$lte: 16}, "warehouseLocation.latitude": {$gte: 60} }).explain("executionStats")
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "mylearning.products",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "$and" : [
                                {
                                        "price" : {
                                                "$lte" : 16
                                        }
                                },
                                {
                                        "warehouseLocation.latitude" : {
                                                "$gte" : 60
                                        }
                                }
                        ]
                },
                "winningPlan" : {
                        "stage" : "FETCH",
                        "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                        "price" : 1,
                                        "warehouseLocation.latitude" : 1
                                },
                                "indexName" : "price_1_warehouseLocation.latitude_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                        "price" : [ ],
                                        "warehouseLocation.latitude" : [ ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2,
                                "direction" : "forward",
                                "indexBounds" : {
                                        "price" : [
                                                "[-inf.0, 16.0]"
                                        ],
                                        "warehouseLocation.latitude" : [
                                                "[60.0, inf.0]"
                                        ]
                                }
                        }
                },
                "rejectedPlans" : [ ]
        },
        "executionStats" : {
                "executionSuccess" : true,
                "nReturned" : 1,
                "executionTimeMillis" : 1089,
                "totalKeysExamined" : 5,
                "totalDocsExamined" : 1,
                "executionStages" : {
                        "stage" : "FETCH",
                        "nReturned" : 1,
                        "executionTimeMillisEstimate" : 310,
                        "works" : 5,
                        "advanced" : 1,
                        "needTime" : 3,
                        "needYield" : 0,
                        "saveState" : 2,
                        "restoreState" : 2,
                        "isEOF" : 1,
                        "invalidates" : 0,
                        "docsExamined" : 1,
                        "alreadyHasObj" : 0,
                        "inputStage" : {
                                "stage" : "IXSCAN",
                                "nReturned" : 1,
                                "executionTimeMillisEstimate" : 270,
                                "works" : 5,
                                "advanced" : 1,
                                "needTime" : 3,
                                "needYield" : 0,
                                "saveState" : 2,
                                "restoreState" : 2,
                                "isEOF" : 1,
                                "invalidates" : 0,
                                "keyPattern" : {
                                        "price" : 1,
                                        "warehouseLocation.latitude" : 1
                                },
                                "indexName" : "price_1_warehouseLocation.latitude_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                        "price" : [ ],
                                        "warehouseLocation.latitude" : [ ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2,
                                "direction" : "forward",
                                "indexBounds" : {
                                        "price" : [
                                                "[-inf.0, 16.0]"
                                        ],
                                        "warehouseLocation.latitude" : [
                                                "[60.0, inf.0]"
                                        ]
                                },
                                "keysExamined" : 5,
                                "seeks" : 4,
                                "dupsTested" : 0,
                                "dupsDropped" : 0,
                                "seenInvalidated" : 0
                        }
                }
        },
        "serverInfo" : {
                "host" : "PC292716",
                "port" : 27017,
                "version" : "3.4.9",
                "gitVersion" : "876ebee8c7dd0e2d992f36a848ff4dc50ee6603e"
        },
        "ok" : 1
}
MongoDB Enterprise &gt; db.products.find({ "price": {$lte: 16}, "warehouseLocation.latitude": {$gte: 60} })
{ "_id" : ObjectId("5a9e790a1ae1f955c1a70c4a"), "id" : 5, "name" : "Doll", "price" : 10.5, "dimensions" : { "length" : 5.1, "width" : 1, "height" : 7 }, "warehouseLocation" : { "latitude" : 64.4, "longitude" : -82.7 } }
MongoDB Enterprise &gt;</pre>
<p>Yeah, we got <em>&#8220;docsExamined&#8221; : 1 </em>, that&#8217;s the way to go. Go create some indexes on your top most queries, you can definitely see some magics over there. You can create up to 64 indexes on a collection in MongoDB, but you may need to create only few, only on your top result queries. What you can do is, whenever you are facing any performance issues on any queries, consider that it needs some tuning and definitely a Index. There are so many other complex Indexes, but widely used Indexes are single key index and compound index.</p>
<p>With that, we are done with this post. I will be posting the continuation part of this series very soon. Till then, bye.</p>
<h2><span id="conclusion">Conclusion</span></h2>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/continue-with-learning-indexes-in-mongodb/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Learn MongoDB With Me &#8211; Part 2</title>
		<link>https://mail.sibeeshpassion.com/learn-mongodb-with-me-part-2/</link>
					<comments>https://mail.sibeeshpassion.com/learn-mongodb-with-me-part-2/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Fri, 02 Mar 2018 08:18:23 +0000</pubDate>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Mongo CLI Commands]]></category>
		<category><![CDATA[Mongo Commands]]></category>
		<category><![CDATA[Mongo Shells]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12654</guid>

					<description><![CDATA[[toc] Introduction This is the second article of the series &#8220;Learn MongoDB with me&#8221;, if you haven&#8217;t read my previous post on this topic, I strongly recommend you to find it here. This is the continuation of exploring the Mongo shells, we will be performing some commands on the Mongo shells. For easy reference I will try to add screenshots for each steps I am following. I hope it will help you come along with me. Thanks for reading. Background Like I said, it is going to be the second part of the series. I believe that you have enough [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>This is the second article of the series &#8220;Learn MongoDB with me&#8221;, if you haven&#8217;t read my previous post on this topic, I strongly recommend you to find it <a href="http://sibeeshpassion.com/category/mongodb/">here</a>. This is the continuation of exploring the Mongo shells, we will be performing some commands on the Mongo shells. For easy reference I will try to add screenshots for each steps I am following. I hope it will help you come along with me. Thanks for reading.</p>
<h2>Background</h2>
<p>Like I said, it is going to be the second part of the series. I believe that you have enough knowledge about Mongo DB and how to set up it? How a Mongo shells can be used? If you are not able to answer these question yourself, please consider reading my <a href="http://sibeeshpassion.com/category/mongodb/">previous posts</a> again.</p>
<h2>Mongo shells, the perfect CLI</h2>
<p>We can do anything in the Mongo shell, to make the statement clear. I am going to perform some CRUD operations (Create, Read, Update, Delete) within Mongo shells. To do so, we can use Mongo import commands. The Mongo import commands can do the work for you, even if the data is in .tsv, .csv, .json etc. Let&#8217;s see those in action.</p>
<p>As a first step, let us see some documentation.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">C:\Program Files\MongoDB\Server\3.4\bin&gt;mongoimport --help</pre>
<p>The above command will give you all the options available to get started.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">Usage:
  mongoimport &lt;options&gt; &lt;file&gt;

Import CSV, TSV or JSON data into MongoDB. If no file is provided, mongoimport reads from stdin.

See http://docs.mongodb.org/manual/reference/program/mongoimport/ for more information.

general options:
      /help                                       print usage
      /version                                    print the tool version and
                                                  exit

verbosity options:
  /v, /verbose:&lt;level&gt;                            more detailed log output
                                                  (include multiple times for
                                                  more verbosity, e.g. -vvvvv,
                                                  or specify a numeric value,
                                                  e.g. --verbose=N)
      /quiet                                      hide all log output

connection options:
  /h, /host:&lt;hostname&gt;                            mongodb host to connect to
                                                  (setname/host1,host2 for
                                                  replica sets)
      /port:&lt;port&gt;                                server port (can also use
                                                  --host hostname:port)

kerberos options:
      /gssapiServiceName:&lt;service-name&gt;           service name to use when
                                                  authenticating using
                                                  GSSAPI/Kerberos ('mongodb' by
                                                  default)
      /gssapiHostName:&lt;host-name&gt;                 hostname to use when
                                                  authenticating using
                                                  GSSAPI/Kerberos (remote
                                                  server's address by default)

ssl options:
      /ssl                                        connect to a mongod or mongos
                                                  that has ssl enabled
      /sslCAFile:&lt;filename&gt;                       the .pem file containing the
                                                  root certificate chain from
                                                  the certificate authority
      /sslPEMKeyFile:&lt;filename&gt;                   the .pem file containing the
                                                  certificate and key
      /sslPEMKeyPassword:&lt;password&gt;               the password to decrypt the
                                                  sslPEMKeyFile, if necessary
      /sslCRLFile:&lt;filename&gt;                      the .pem file containing the
                                                  certificate revocation list
      /sslAllowInvalidCertificates                bypass the validation for
                                                  server certificates
      /sslAllowInvalidHostnames                   bypass the validation for
                                                  server name
      /sslFIPSMode                                use FIPS mode of the
                                                  installed openssl library

authentication options:
  /u, /username:&lt;username&gt;                        username for authentication
  /p, /password:&lt;password&gt;                        password for authentication
      /authenticationDatabase:&lt;database-name&gt;     database that holds the
                                                  user's credentials
      /authenticationMechanism:&lt;mechanism&gt;        authentication mechanism to
                                                  use

namespace options:
  /d, /db:&lt;database-name&gt;                         database to use
  /c, /collection:&lt;collection-name&gt;               collection to use

uri options:
      /uri:mongodb-uri                            mongodb uri connection string

input options:
  /f, /fields:&lt;field&gt;[,&lt;field&gt;]*                  comma separated list of
                                                  fields, e.g. -f name,age
      /fieldFile:&lt;filename&gt;                       file with field names - 1 per
                                                  line
      /file:&lt;filename&gt;                            file to import from; if not
                                                  specified, stdin is used
      /headerline                                 use first line in input
                                                  source as the field list (CSV
                                                  and TSV only)
      /jsonArray                                  treat input source as a JSON
                                                  array
      /parseGrace:&lt;grace&gt;                         controls behavior when type
                                                  coercion fails - one of:
                                                  autoCast, skipField, skipRow,
                                                  stop (defaults to 'stop')
                                                  (default: stop)
      /type:&lt;type&gt;                                input format to import: json,
                                                  csv, or tsv (defaults to
                                                  'json') (default: json)
      /columnsHaveTypes                           indicated that the field list
                                                  (from --fields, --fieldsFile,
                                                  or --headerline) specifies
                                                  types; They must be in the
                                                  form of
                                                  '&lt;colName&gt;.&lt;type&gt;(&lt;arg&gt;)'.
                                                  The type can be one of: auto,
                                                  binary, bool, date, date_go,
                                                  date_ms, date_oracle, double,
                                                  int32, int64, string. For
                                                  each of the date types, the
                                                  argument is a datetime layout
                                                  string. For the binary type,
                                                  the argument can be one of:
                                                  base32, base64, hex. All
                                                  other types take an empty
                                                  argument. Only valid for CSV
                                                  and TSV imports. e.g.
                                                  zipcode.string(),
                                                  thumbnail.binary(base64)

ingest options:
      /drop                                       drop collection before
                                                  inserting documents
      /ignoreBlanks                               ignore fields with empty
                                                  values in CSV and TSV
      /maintainInsertionOrder                     insert documents in the order
                                                  of their appearance in the
                                                  input source
  /j, /numInsertionWorkers:&lt;number&gt;               number of insert operations
                                                  to run concurrently (defaults
                                                  to 1) (default: 1)
      /stopOnError                                stop importing at first
                                                  insert/upsert error
      /mode:[insert|upsert|merge]                 insert: insert only. upsert:
                                                  insert or replace existing
                                                  documents. merge: insert or
                                                  modify existing documents.
                                                  defaults to insert
      /upsertFields:&lt;field&gt;[,&lt;field&gt;]*            comma-separated fields for
                                                  the query part when --mode is
                                                  set to upsert or merge
      /writeConcern:&lt;write-concern-specifier&gt;     write concern options e.g.
                                                  --writeConcern majority,
                                                  --writeConcern '{w: 3,
                                                  wtimeout: 500, fsync: true,
                                                  j: true}'
      /bypassDocumentValidation                   bypass document validation</pre>
<h3>Insert data to MondoDB using Mongo shell</h3>
<p>Now let&#8217;s say I have a following JSON data, and we are going to insert the same to our db collection.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">[ 
{
 "color": "black",
 "category": "hue",
 "type": "primary",
 "code": {
 "rgba": [255,255,255,1],
 "hex": "#000"
 }
 },
 {
 "color": "white",
 "category": "value",
 "code": {
 "rgba": [0,0,0,1],
 "hex": "#FFF"
 }
 },
 {
 "color": "red",
 "category": "hue",
 "type": "primary",
 "code": {
 "rgba": [255,0,0,1],
 "hex": "#FF0"
 }
 },
 {
 "color": "blue",
 "category": "hue",
 "type": "primary",
 "code": {
 "rgba": [0,0,255,1],
 "hex": "#00F"
 }
 },
 {
 "color": "yellow",
 "category": "hue",
 "type": "primary",
 "code": {
 "rgba": [255,255,0,1],
 "hex": "#FF0"
 }
 },
 {
 "color": "green",
 "category": "hue",
 "type": "secondary",
 "code": {
 "rgba": [0,255,0,1],
 "hex": "#0F0"
 }
 }
]</pre>
<p>To do so, we need to use the following command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">C:\Program Files\MongoDB\Server\3.4\bin&gt;mongoimport --db mylearning --collection colors --jsonArray --file colors.json</pre>
<p>Here, as you can see, we are providing the db name, collection, name, what is the data type of the file and finally the file name.</p>
<p>If you ever get the error as &#8220;Failed: open colors.json: The system cannot find the file specified.&#8221;, please make sure that the document is in the server folder, in my case it is &#8220;C:\Program Files\MongoDB\Server\3.4\bin&#8221;. If everything is fine, you will be able to see an output as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">C:\Program Files\MongoDB\Server\3.4\bin&gt;mongoimport --db mylearning --collection colors --jsonArray --file colors.json
2018-03-01T16:35:35.470+0530    connected to: localhost
2018-03-01T16:35:36.012+0530    imported 6 documents

C:\Program Files\MongoDB\Server\3.4\bin&gt;</pre>
<h3>Reading the data from a collection in MongoDB</h3>
<p>Now that, we have colors collection, let&#8217;s go and check whether the database has the data we are expecting.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">C:\Program Files\MongoDB\Server\3.4\bin&gt;mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
Server has startup warnings:
2018-03-01T16:24:43.793+0530 I CONTROL  [initandlisten]
2018-03-01T16:24:43.793+0530 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2018-03-01T16:24:43.793+0530 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2018-03-01T16:24:43.793+0530 I CONTROL  [initandlisten]
MongoDB Enterprise &gt; use mylearning
switched to db mylearning
MongoDB Enterprise &gt; show collections
chats
colors
messages
MongoDB Enterprise &gt; db.colors.count
function (query, options) {
    query = this.find(query);

    // Apply options and return the result of the find
    return QueryHelpers._applyCountOptions(query, options).count(true);
}
MongoDB Enterprise &gt; db.colors.count()
6
MongoDB Enterprise &gt;</pre>
<p>When you use <em>count,</em> make sure you are treating it as a function as <em>count(). </em>We have the count as 6, and that&#8217;s what we are expecting. Am I right? Don&#8217;t you think, that we should go fetch some data from that collection, yeah with some filter?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.colors.find({"type": "primary"})
{ "_id" : ObjectId("5a97de7f2fcdf731d255a19d"), "color" : "black", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 255, 255, 1 ], "hex" : "#000" } }
{ "_id" : ObjectId("5a97de7f2fcdf731d255a19e"), "color" : "yellow", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 255, 0, 1 ], "hex" : "#FF0" } }
{ "_id" : ObjectId("5a97de7f2fcdf731d255a1a1"), "color" : "red", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 0, 0, 1 ], "hex" : "#FF0" } }
{ "_id" : ObjectId("5a97de7f2fcdf731d255a1a2"), "color" : "blue", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 0, 0, 255, 1 ], "hex" : "#00F" } }
MongoDB Enterprise &gt;</pre>
<p>We have successfully imported that data, and we have fetched the colors with type as primary. I think, there should be a custom color, which has the type as primary. Can we do that now?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.colors.insert({
... "color": "custome",
...  "category": "hue",
...  "type": "primary",
...  "code": {
...  "rgba": [255,1,255,1],
...  "hex": "#FF1"
...  }
... }
... )
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise &gt;</pre>
<p>Now if you run our previous query, you can see an output as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.colors.find({"type": "primary"})
{ "_id" : ObjectId("5a97de7f2fcdf731d255a19d"), "color" : "black", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 255, 255, 1 ], "hex" : "#000" } }
{ "_id" : ObjectId("5a97de7f2fcdf731d255a19e"), "color" : "yellow", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 255, 0, 1 ], "hex" : "#FF0" } }
{ "_id" : ObjectId("5a97de7f2fcdf731d255a1a1"), "color" : "red", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 0, 0, 1 ], "hex" : "#FF0" } }
{ "_id" : ObjectId("5a97de7f2fcdf731d255a1a2"), "color" : "blue", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 0, 0, 255, 1 ], "hex" : "#00F" } }
{ "_id" : ObjectId("5a97e3202c19f0e958477e06"), "color" : "custome", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 1, 255, 1 ], "hex" : "#FF1" } }
MongoDB Enterprise &gt;</pre>
<h3>Updating a document in MongoDB</h3>
<p>Wow, we have the data now. And we performed, Create and Read operations on our DB. It is time for updating the document. Let&#8217;s go ahead and add a new property &#8220;manuallyCreated&#8221; to the color we have created. It is going to help us in finding this kind of entries easily.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.colors.update({
... "color":"custome"
... }
... ,{
... $set:{"manuallyCreated":"True"}}
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
MongoDB Enterprise &gt;</pre>
<p>Let&#8217;s find all the manually created colors now, and yeah we know there is going to be one record.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.colors.find({"manuallyCreated":"True"})
{ "_id" : ObjectId("5a97e3202c19f0e958477e06"), "color" : "custome", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 1, 255, 1 ], "hex" : "#FF1" }, "manuallyCreated" : "True" }
MongoDB Enterprise &gt;</pre>
<p>Let&#8217;s update the color name to &#8220;custom&#8221; instead of &#8220;custome&#8221;, sorry for the typo.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.colors.update({"_id" : ObjectId("5a97e3202c19f0e958477e06")},
... {$set:{"color":"custom"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
MongoDB Enterprise &gt;</pre>
<p>Ah, I made a mistake. I ran the following query by mistake.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.colors.update({ "color":"custom" } ,{ $set:{"code.rgba" : [ 255, 1, 255]}} )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })</pre>
<p>Do you know, what that query just did? It just updated the rgba of our custom color to three point array &#8220;[ 255, 1, 255]&#8221;. That&#8217;s not what I wanted. Now what we can do? We need to add one value to that set. Let&#8217;s do that now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.colors.update({ "color":"custom" } ,{ $addToSet:{"code.rgba" : "1" }} )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="null">MongoDB Enterprise &gt; db.colors.find({"manuallyCreated":"True"})
{ "_id" : ObjectId("5a97e3202c19f0e958477e06"), "color" : "custom", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 1, 255, "1" ], "hex" : "#FF1" }, "manuallyCreated" : "True" }
MongoDB Enterprise &gt;</pre>
<p>Please be noted that, there is one more update, which will just update the entire document. In this case, if you are not providing the value for each attributes, it will be overwriting the same. Let&#8217;s see an example.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.colors.update({"color":"red"},{"color":"test"})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
MongoDB Enterprise &gt; db.colors.find({})</pre>
<p>Here we just give a command to update the color red to color test, as we have not provided other attributes as part of our query, after running the query, there will be only one attribute that is color.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.colors.find({})
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f1"), "color" : "black", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 255, 255, 1 ], "hex" : "#000" } }
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f2"), "color" : "test" }
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f3"), "color" : "white", "category" : "value", "code" : { "rgba" : [ 0, 0, 0, 1 ], "hex" : "#FFF" } }
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f4"), "color" : "blue", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 0, 0, 255, 1 ], "hex" : "#00F" } }
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f5"), "color" : "yellow", "category" : "hue", "type" : "primary", "code" : { "rgba" : [ 255, 255, 0, 1 ], "hex" : "#FF0" } }
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f6"), "color" : "green", "category" : "hue", "type" : "secondary", "code" : { "rgba" : [ 0, 255, 0, 1 ], "hex" : "#0F0" } }
MongoDB Enterprise &gt; db.colors.find({"color":"test"})
{ "_id" : ObjectId("5a97f73f2fcdf731d255a1f2"), "color" : "test" }
MongoDB Enterprise &gt;</pre>
<h3>Deleting a document in MongoDB shell</h3>
<p>So, we added a custom color, and later we found that it is no more needed in our document as we found an exact match with a different color. Now we need to remove the one we have added.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.colors.remove({"color":"custom"})
WriteResult({ "nRemoved" : 1 })
MongoDB Enterprise &gt;</pre>
<p>Let&#8217;s go and check again whether it is actually removed or not.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.colors.find({"color":"custom"})
MongoDB Enterprise &gt;</pre>
<p>The find query returns no records.</p>
<h2>Deleting an entire collection</h2>
<p>We have performed CRUD operations on a collection, what if we need to remove the entire collection?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.colors.drop()
true
MongoDB Enterprise &gt;</pre>
<p>&nbsp;</p>
<p>With that, we are done with this post. I will be posting the continuation part of this series very soon. Till then, bye.</p>
<h2><span id="conclusion">Conclusion</span></h2>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/learn-mongodb-with-me-part-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Learn MongoDB With Me</title>
		<link>https://mail.sibeeshpassion.com/learn-mongodb-with-me/</link>
					<comments>https://mail.sibeeshpassion.com/learn-mongodb-with-me/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 22 Feb 2018 05:03:00 +0000</pubDate>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Indexes in MongoDB]]></category>
		<category><![CDATA[MongoDB Basics]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Why MongoDB]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12641</guid>

					<description><![CDATA[[toc] Introduction This is going to be a series of article on MongoDB. Here we are going to do some exercises with MongoDB, we will be talking about Mongo Shell, how can we configure MongoDB?, What are Indexes in MongoDB etc. We all know what an Indexes is, you might have already done that with any relational databases like SQL and MySQL . Have you every done indexing for your MongoDB? If your answer is &#8220;no&#8221;, no worries, here we are going to see indexes in MongoDB , if it is a &#8220;yes&#8221; please read this post and correct me if I am [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>This is going to be a series of article on MongoDB. Here we are going to do some exercises with MongoDB, we will be talking about Mongo Shell, how can we configure MongoDB?, What are Indexes in MongoDB etc. We all know what an Indexes is, you might have already done that with any relational databases like <a href="http://sibeeshpassion.com/category/SQL/">SQL</a> and <a href="http://sibeeshpassion.com/category/MySQL/">MySQL</a> . Have you every done indexing for your MongoDB? If your answer is &#8220;no&#8221;, no worries, here we are going to see indexes in <a href="http://sibeeshpassion.com/category/mongodb/">MongoDB</a> , if it is a &#8220;yes&#8221; please read this post and correct me if I am wrong anywhere. Let&#8217;s begin now.</p>
<h2>Prerequisites</h2>
<p>I hope you might have got a basic information about MongoDB, if not, I strongly recommend you to read <a href="http://sibeeshpassion.com/category/mongodb/">these posts</a>. Now that, you have a basic idea, I am assuming that you have already set up the environment for MongoDB development. Let&#8217;s recall what you might have done so far.</p>
<ol>
<li>Install MongoDB</li>
<li>Set the environment variable for MongoDB</li>
<li>Start the MongoDB services</li>
</ol>
<p>To set the environment variable for MongoDB, you may have to add a new path to the system variable path with the value as &#8220;C:\Program Files\MongoDB\Server\3.4\bin&#8221;, please note that the version number will be varied according to your MongoDB version. Once you are done the above steps, you should be able to start both Mongo server and Mongo shell from the command line interface.</p>
<h2>Setting up MongoDB using CLI</h2>
<p>Now let&#8217;s just open our command line interface, and create the data directory for Mongo. We will have to create a directory for the same. Please go along with the below commands.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">md \data
md \data\db
mongod</pre>
<p>Now let&#8217;s open a new CLI and run the command &#8220;mongo&#8221;, please do not worry about the warnings you are getting, as we are not working in production data, we may not need to secure and optimize it.</p>
<p><a href="http://sibeeshpassion.com/wp-content/uploads/2018/02/Mongo-Command.png"><img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-12643" src="http://sibeeshpassion.com/wp-content/uploads/2018/02/Mongo-Command.png" alt="" width="472" height="176" srcset="/wp-content/uploads/2018/02/Mongo-Command.png 472w, /wp-content/uploads/2018/02/Mongo-Command-300x112.png 300w, /wp-content/uploads/2018/02/Mongo-Command-400x149.png 400w" sizes="(max-width: 472px) 100vw, 472px" /></a></p>
<h2>Exploring MongoDB</h2>
<p>Once you are connected to MongoDB, by default you are connected to test DB. You can check that by running the command <code class="EnlighterJSRAW" data-enlighter-language="null">MongoDB Enterprise &gt; db</code></p>
<h3>Playing with Mongo Shell</h3>
<p>Let&#8217;s just use a new database now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; use MongoIndex
switched to db MongoIndex
MongoDB Enterprise &gt;</pre>
<p>Please be noted that the database MongoIndex doesn&#8217;t exist as of now, as we haven&#8217;t created it. Still, Mongo just switched our context to the new database. You can see this if you run the command <code class="EnlighterJSRAW" data-enlighter-language="shell">show dbs</code></p>
<p>The database will be created once we insert any document associated with it. Now we are going to create a new collection called &#8220;User&#8221;, so once we made the entry to this collection, the database will also be created automatically. Let&#8217;s do that.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.users.insert({"name":"Sibees Venu"})
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise &gt;</pre>
<p>Now if you run the &#8220;show dbs&#8221; command again, the database MongoIndex will show up. If you ever need to see the collections you have in the DB, you just need to run the command &#8220;show collections&#8221;.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; show collections
users
MongoDB Enterprise &gt;</pre>
<p>The MongoDB is very friendly when it comes to data, it doesn&#8217;t require any schema to get it started. The learning is so easy, am I right?</p>
<p>The other benefit of MongoDB is its <a href="http://sibeeshpassion.com/category/javascript/">JavaScript</a> interpreted shell, where we can actually type JavaScript code and run. To test it out, let&#8217;s create a variable and use it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; var name = "Sibeesh Venu"
MongoDB Enterprise &gt; name
Sibeesh Venu
MongoDB Enterprise &gt;</pre>
<p>This way, we can interact with the database with a JavaScript program. Now let&#8217;s go ahead and creating a collection called &#8220;Numbers&#8221; and insert 26,000 rows in it. So how are we going to do that? Yes, you are right, we are going to write a for loop, the mongo shell gives that kind of flexibility. Let&#8217;s see that in action.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; for(i=0;i&lt;=26000;i++){
... db.Numbers.insert({
... "number":i
... })
... }
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise &gt;</pre>
<p>So we have done that. Note that, we are able to break the commands into multiple lines, this allows to break the complex codes to much readable format in the shell itself. Sounds good?</p>
<p>Even though we have inserted 26,000 rows,  it always shows,<code class="EnlighterJSRAW" data-enlighter-language="shell">"nInserted" : 1</code> this is because it is counting a number of operations, not the individual documents. Let&#8217;s see this by checking the count now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.numbers.count()
0
MongoDB Enterprise &gt; db.Numbers.count()
26001
MongoDB Enterprise &gt;</pre>
<p>Please note that it is case sensitive.</p>
<h3>Indexes in MongoDB</h3>
<p>Now if you need to see any particular record,  you can always write the query in the shell as follows.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.Numbers.find(
... {"number":24000}
... )
{ "_id" : ObjectId("5a8d3be2020a0071d115cf62"), "number" : 24000 }
MongoDB Enterprise &gt;</pre>
<p>So in the query, we are using the function &#8220;find&#8221; with the filter &#8220;number: 24000&#8221;, so that the Mongo can return the record which has the number value as 24000. Now that we have got the output we needed, would you like to see what just happened in the background? To do so, we can use the function &#8220;explain()&#8221;.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.Numbers.find( {"number":24000} ).explain()
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "MongoIndex.Numbers",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "number" : {
                                "$eq" : 24000
                        }
                },
                "winningPlan" : {
                        "stage" : "COLLSCAN",
                        "filter" : {
                                "number" : {
                                        "$eq" : 24000
                                }
                        },
                        "direction" : "forward"
                },
                "rejectedPlans" : [ ]
        },
        "serverInfo" : {
                "host" : "PC292716",
                "port" : 27017,
                "version" : "3.4.9",
                "gitVersion" : "876ebee8c7dd0e2d992f36a848ff4dc50ee6603e"
        },
        "ok" : 1
}
MongoDB Enterprise &gt;</pre>
<p>And, if you need to get more information about the execution, you can pass the parameter &#8220;executionStats&#8221; to the &#8220;explain&#8221; function.</p>
<blockquote><p>The parameter is always case sensitive, you will get an errors as below, if you give it wrong. So please make sure you are passing executionStats not executionstats.</p>
<p>&#8220;MongoDB Enterprise &gt; db.Numbers.find( {&#8220;number&#8221;:24000} ).explain(&#8220;executionstats&#8221;)<br />
2018-02-21T15:12:34.197+0530 E QUERY [thread1] Error: explain verbosity must be one of {&#8216;queryPlanner&#8217;,&#8217;executionStats&#8217;,&#8217;allPlansExecution&#8217;} :<br />
parseVerbosity@src/mongo/shell/explainable.js:22:1<br />
constructor@src/mongo/shell/explain_query.js:83:27<br />
DBQuery.prototype.explain@src/mongo/shell/query.js:520:24<br />
@(shell):1:1&#8243;</p></blockquote>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.Numbers.find( {"number":24000} ).explain("executionStats")
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "MongoIndex.Numbers",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "number" : {
                                "$eq" : 24000
                        }
                },
                "winningPlan" : {
                        "stage" : "COLLSCAN",
                        "filter" : {
                                "number" : {
                                        "$eq" : 24000
                                }
                        },
                        "direction" : "forward"
                },
                "rejectedPlans" : [ ]
        },
        "executionStats" : {
                "executionSuccess" : true,
                "nReturned" : 1,
                "executionTimeMillis" : 13,
                "totalKeysExamined" : 0,
                "totalDocsExamined" : 26001,
                "executionStages" : {
                        "stage" : "COLLSCAN",
                        "filter" : {
                                "number" : {
                                        "$eq" : 24000
                                }
                        },
                        "nReturned" : 1,
                        "executionTimeMillisEstimate" : 11,
                        "works" : 26003,
                        "advanced" : 1,
                        "needTime" : 26001,
                        "needYield" : 0,
                        "saveState" : 203,
                        "restoreState" : 203,
                        "isEOF" : 1,
                        "invalidates" : 0,
                        "direction" : "forward",
                        "docsExamined" : 26001
                }
        },
        "serverInfo" : {
                "host" : "PC292716",
                "port" : 27017,
                "version" : "3.4.9",
                "gitVersion" : "876ebee8c7dd0e2d992f36a848ff4dc50ee6603e"
        },
        "ok" : 1
}
MongoDB Enterprise &gt;</pre>
<p>Now you can see more information on the execution of how much time it took for the execution and how many docs it is examined etc. If you have noticed, it has examined all the 26001 records and took 13 milliseconds. That&#8217;s just a case, that we had only less number of records in the table, what if, we have millions of records in it? And examining all the records would be a bad idea, am I right? So what do we do at that time? What would be a permanent solution for this? This is where the importance of <em>Indexes</em> comes into action.</p>
<p>Let&#8217;s create an Index for the number that we are going to search.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.Numbers.createIndex({number:1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
MongoDB Enterprise &gt;</pre>
<p>Here the number is a special variable, not a string. As you can see, we had created the index. You can see that the property value of createdCollectionAutomatically is false, as the collection had already created and it didn&#8217;t have to create it again.</p>
<p>Let&#8217;s run our find query again.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">MongoDB Enterprise &gt; db.Numbers.find( {"number":24000} ).explain("executionStats")
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "MongoIndex.Numbers",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "number" : {
                                "$eq" : 24000
                        }
                },
                "winningPlan" : {
                        "stage" : "FETCH",
                        "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                        "number" : 1
                                },
                                "indexName" : "number_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                        "number" : [ ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2,
                                "direction" : "forward",
                                "indexBounds" : {
                                        "number" : [
                                                "[24000.0, 24000.0]"
                                        ]
                                }
                        }
                },
                "rejectedPlans" : [
                        {
                                "stage" : "FETCH",
                                "inputStage" : {
                                        "stage" : "IXSCAN",
                                        "keyPattern" : {
                                                "number" : 24000
                                        },
                                        "indexName" : "number_24000",
                                        "isMultiKey" : false,
                                        "multiKeyPaths" : {
                                                "number" : [ ]
                                        },
                                        "isUnique" : false,
                                        "isSparse" : false,
                                        "isPartial" : false,
                                        "indexVersion" : 2,
                                        "direction" : "forward",
                                        "indexBounds" : {
                                                "number" : [
                                                        "[24000.0, 24000.0]"
                                                ]
                                        }
                                }
                        }
                ]
        },
        "executionStats" : {
                "executionSuccess" : true,
                "nReturned" : 1,
                "executionTimeMillis" : 36,
                "totalKeysExamined" : 1,
                "totalDocsExamined" : 1,
                "executionStages" : {
                        "stage" : "FETCH",
                        "nReturned" : 1,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 3,
                        "advanced" : 1,
                        "needTime" : 0,
                        "needYield" : 0,
                        "saveState" : 1,
                        "restoreState" : 1,
                        "isEOF" : 1,
                        "invalidates" : 0,
                        "docsExamined" : 1,
                        "alreadyHasObj" : 0,
                        "inputStage" : {
                                "stage" : "IXSCAN",
                                "nReturned" : 1,
                                "executionTimeMillisEstimate" : 0,
                                "works" : 2,
                                "advanced" : 1,
                                "needTime" : 0,
                                "needYield" : 0,
                                "saveState" : 1,
                                "restoreState" : 1,
                                "isEOF" : 1,
                                "invalidates" : 0,
                                "keyPattern" : {
                                        "number" : 1
                                },
                                "indexName" : "number_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                        "number" : [ ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2,
                                "direction" : "forward",
                                "indexBounds" : {
                                        "number" : [
                                                "[24000.0, 24000.0]"
                                        ]
                                },
                                "keysExamined" : 1,
                                "seeks" : 1,
                                "dupsTested" : 0,
                                "dupsDropped" : 0,
                                "seenInvalidated" : 0
                        }
                }
        },
        "serverInfo" : {
                "host" : "PC292716",
                "port" : 27017,
                "version" : "3.4.9",
                "gitVersion" : "876ebee8c7dd0e2d992f36a848ff4dc50ee6603e"
        },
        "ok" : 1
}
MongoDB Enterprise &gt;</pre>
<p>As we had given the index on what exactly we are going to search, it just examined only that document when we run the query, that&#8217;s why the value of the property <em>totalDocsExamined </em>is 1. Indexing will not have many impacts on the database which has few records in it, but it has a massive effect on very large data sets which has millions of records in it. Using this simple Indexes can reduce the execution time to almost nothing.</p>
<p>With that, we are done with this post. I will be posting the continuation part of this series very soon. Till then, bye.</p>
<h2><span id="conclusion">Conclusion</span></h2>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/learn-mongodb-with-me/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Creating a Chat Application in Node JS with Express, MongoDB, Mongoose and Socket.io</title>
		<link>https://mail.sibeeshpassion.com/creating-a-chat-application-in-node-js-with-express-mongodb-mongoose-and-socket-io/</link>
					<comments>https://mail.sibeeshpassion.com/creating-a-chat-application-in-node-js-with-express-mongodb-mongoose-and-socket-io/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 04 Dec 2017 12:09:50 +0000</pubDate>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Node JS]]></category>
		<category><![CDATA[Chat Application in Node JS]]></category>
		<category><![CDATA[Chat Application using Socket.io]]></category>
		<category><![CDATA[Mongoose]]></category>
		<category><![CDATA[Simple client side chat application]]></category>
		<category><![CDATA[Socket.io]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12595</guid>

					<description><![CDATA[[toc] Introduction In this article, we are going to a chat application in Node JS  with the back end MongoDB.  We will also be using Mongoose for creating the MongoDB models and Socket.io for making multi directional chats on multiple client window. If you are really new to the Node JS, I strongly recommend you to read some articles on the same here. You can also see how you can create a sample Node application with MongoDB and Mongoose here. At the end of this article, I guarantee that you will be having some basic knowledge on the mentioned technologies. I hope you will [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>In this article, we are going to a chat application in <a href="http://sibeeshpassion.com/category/Node-JS/">Node JS</a>  with the back end <a href="http://sibeeshpassion.com/category/MongoDB">MongoDB.</a>  We will also be using <a href="http://sibeeshpassion.com/tag/Mongoose/">Mongoose</a> for creating the MongoDB models and <a href="http://sibeeshpassion.com/tag/Socket.io/">Socket.io</a> for making multi directional chats on multiple client window. If you are really new to the Node JS, I strongly recommend you to read some articles on the same <a href="http://sibeeshpassion.com/category/Node-JS/">here</a>. You can also see how you can create a sample Node application with MongoDB and Mongoose <a href="http://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/">here</a>. At the end of this article, I guarantee that you will be having some basic knowledge on the mentioned technologies. I hope you will like this article.</p>
<h3><span id="source-code">Source Code</span></h3>
<p>You can always clone or download the source code <a href="https://code.msdn.microsoft.com/ChatApp-NodeJS-Socketio-22325371">here</a></p>
<h3>Background</h3>
<p>Creating a chat application is always an interesting this to do. And it is a good way to learn a lot, because you are creating some interactions on your application. And with the release of few technologies we can create such application without any hassle. It is much more easier than ever. Here we are also going to create a chat application. A basic knowledge of Node JS, MongoDB, JavaScript, JQuery is more than enough to create this project. So, please be with me. Let&#8217;s just skip the talking and start developing.</p>
<h3>Setting up Node application</h3>
<p>This step requires some basic knowledge, please see some of that <a href="http://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/">here</a>.  So as mentioned in that article, we have successfully created our Package.json file and installed the required packages. Let&#8217;s review our package.json file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
 "name": "chatapp",
 "version": "1.0.0",
 "description": "A chat application in Node JS, which uses MongoDB, Mongoose and Socket.io",
 "main": "index.js",
 "scripts": {
 "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
 },
 "keywords": [
 "Node",
 "JS",
 "MongoDB",
 "Mongoose",
 "Socket.io"
 ],
 "author": "Sibeesh Venu",
 "license": "ISC",
 "dependencies": {
 }
}
</pre>
<p>Let&#8217;s install the packages now by running the below commands.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm install --save express
npm install --save mongoose
npm install --save body-parser
npm install --save socket.io</pre>
<p>Now that we have all the dependencies added to the package.json file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">"dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "mongoose": "^4.13.6",
    "socket.io": "^2.0.4"
  }</pre>
<h4>Creating an App using Express</h4>
<p>Let&#8217;s create a file server.js and build an app using Express.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var express = require("express")
var app = express()
app.listen(3020,()=&gt;{
 console.log("Well done, now I am listening...")
})</pre>
<p>I hope you are getting  the desired output, if not, please don&#8217;t worry, just double check the codes you had written.</p>
<h4>Running our application on browser</h4>
<p>Let&#8217;s run our application on port 3020 and see what we are getting <a href="http://localhost:3020/">http://localhost:3020/</a>..</p>
<p>Yes you will get an error as <code class="EnlighterJSRAW" data-enlighter-language="js">Cannot GET /</code>  , no worries. To fix that you need to add the following code block to your server.js file</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.use(express.static(__dirname))</pre>
<h4>Creating Index page</h4>
<p>Here I am going to create a <a href="http://sibeeshpassion.com/category/HTML5/">HTML 5</a> page with <a href="http://sibeeshpassion.com/category/JQuery/">JQuery</a> and Bootstrap referenced in it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;!DOCTYPE html&gt;
&lt;title&gt;Creating a Chat Application in Node JS with Express, MongoDB, Mongoose and Socket.io&lt;/title&gt;
&lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" crossorigin="anonymous"&gt;
&lt;script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous"&gt;&lt;/script&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" crossorigin="anonymous"&gt;&lt;/script&gt;
&lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" crossorigin="anonymous"&gt;&lt;/script&gt;

&lt;div class="container"&gt;
    &lt;br&gt;
    &lt;div class="jumbotron"&gt;
        &lt;h1 class="dispaly-4"&gt;Start Chatting&lt;/h1&gt;
        &lt;br&gt;
        &lt;input id="txtName" class="form-control" placeholder="Name" type="text"&gt;
        &lt;br&gt;
        &lt;textarea id="txtMessage" class="form-control" placeholder="Message"&gt;&lt;/textarea&gt;
        &lt;br&gt;
        &lt;button id="send" class="btn btn-success"&gt;Send&lt;/button&gt;
    &lt;/div&gt;
    &lt;div id="messages"&gt;&lt;/div&gt;
&lt;/div&gt;
</pre>
<p>As you can see, the page has two text boxes and one button. We will be creating some scripts very soon which uses these controls.</p>
<h3>Start developing the chat app</h3>
<p>Till now, it was all basic, and we have done it well. Now it is time to go and write some advanced codes. So, are you ready?</p>
<h4>Create model from page data</h4>
<p>Here we are going to create the model from the page data, that is, from the controls we have in our page. We will be using JQuery to do so.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">&lt;script&gt;
    $(() =&gt; {
        $("send").click(() =&gt; {
            var chatMessage = {
                name: $("#txtName").val(), chat: $("#txtMessage").val()
            }
            postChat(chat)
        })
    })

    function postChat(chat){
        console.log(chat)
    }

&lt;/script&gt;</pre>
<p>Now that we have got the model from the user, let&#8217;s save it to the DB.</p>
<div id="attachment_12596" style="width: 428px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/Model-values-on-browser-console.png"><img decoding="async" aria-describedby="caption-attachment-12596" class="size-full wp-image-12596" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/Model-values-on-browser-console.png" alt="Model values on browser console" width="418" height="446" srcset="/wp-content/uploads/2017/12/Model-values-on-browser-console.png 418w, /wp-content/uploads/2017/12/Model-values-on-browser-console-281x300.png 281w, /wp-content/uploads/2017/12/Model-values-on-browser-console-400x427.png 400w" sizes="(max-width: 418px) 100vw, 418px" /></a><p id="caption-attachment-12596" class="wp-caption-text">Model values on browser console</p></div>
<h4>Setting up database</h4>
<p>We are going to set up our database in mLab as mentioned in this article <a href="http://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/">Using MongoDB on Node JS Application Using Mongoose.</a> So let&#8217;s just require Mongoose and do the needed changes.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var express = require("express")
var mongoose = require("mongoose")

var app = express()

var conString = "mongodb://admin:admin@ds038319.mlab.com:38319/mylearning"
app.use(express.static(__dirname))

var Chats = mongoose.model("Chats", {
    name: String,
    chat: String
})

mongoose.connect(conString, { useMongoClient: true }, (err) =&gt; {
    console.log("Database connection", err)
})

app.listen(3020, () =&gt; {
    console.log("Well done, now I am listening...")
})</pre>
<h4>Creating a Post request</h4>
<p>Now let&#8217;s create a post requests in our index.html file which will the post API in our server.js file.</p>
<p><em><span style="text-decoration: underline;">index.html</span></em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">function postChat(chat) {
        $.post("http://localhost:3020/chats", chat)
}</pre>
<p><span style="text-decoration: underline;"><em>server.js</em></span></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.post("/chats", async (req, res) =&gt; {
    try {
        var chat = new Chats(req.body)
        await chat.save()
        res.sendStatus(200)
    } catch (error) {
        res.sendStatus(500)
        console.error(error)
    }
})
</pre>
<p>Let&#8217;s just run our application and test it out.</p>
<p>You may be getting an error as &#8220;(node:10824) DeprecationWarning: Mongoose: mpromise (mongoose&#8217;s default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html&#8221;&#8221;, here to fix this, we need to use the default promise instead of the Mongoose promise. Let&#8217;s change that. Add this code <code class="EnlighterJSRAW" data-enlighter-language="js">mongoose.Promise = Promise</code> to our server.js file. Give it a try after setting it.</p>
<p>Still it is not working right, you are getting <em>undefined </em>at the place, <code class="EnlighterJSRAW" data-enlighter-language="js">var chat = new Chats(req.body)</code> in our Post API . At this stage, we will have to use our body-parser packages, do you remember the package we have installed? Let&#8217;s just require that package <code class="EnlighterJSRAW" data-enlighter-language="js">var bodyParser = require("body-parser")</code> add the preceding codes to our server.js file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))</pre>
<p>Now this will convert the request to a JSON object by default. Give it a try again, I am sure you will get the actual value instead of undefined.</p>
<h4>Creating a Get request for all the chat data</h4>
<p>We have written codes to write our data into our database, we will have to show this data on our page right? Here we are going to write the get requests in out index.html page which will call the get API.</p>
<p><em><span style="text-decoration: underline;">index.html</span></em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">function getChats() {
     $.get("/chats", (chats) =&gt; {
         chats.forEach(addChat)
     })
}

function addChat(chatObj){
    $("#messages").append(`&lt;h5&gt;${chatObj.name} &lt;/h5&gt;&lt;p&gt;${chatObj.chat}&lt;/p&gt;`);
}</pre>
<p>And call the function getChats() in document ready event.</p>
<p><em><span style="text-decoration: underline;">server.js</span></em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.get("/chats", (req, res) =&gt; {
    Chats.find({}, (error, chats) =&gt; {
        res.send(chats)
    })
})</pre>
<p>Here we are passing {} to our find function, this means, we are going to get all the chats without any filter. Just run your application now, and check whether you are getting the chat messages you had sent.</p>
<div id="attachment_12597" style="width: 369px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/Retreiving-data-from-a-MongoDB.png"><img decoding="async" aria-describedby="caption-attachment-12597" class="size-full wp-image-12597" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/Retreiving-data-from-a-MongoDB.png" alt="Retrieving data from a MongoDB" width="359" height="514" srcset="/wp-content/uploads/2017/12/Retreiving-data-from-a-MongoDB.png 359w, /wp-content/uploads/2017/12/Retreiving-data-from-a-MongoDB-210x300.png 210w" sizes="(max-width: 359px) 100vw, 359px" /></a><p id="caption-attachment-12597" class="wp-caption-text">Retrieving data from a MongoDB</p></div>
<h3>Implementing Socket.io</h3>
<p>Now the chat we are sending is getting saved to our database and we are able to load the same on page load. Is it the behavior of a perfect chat application? Absolutely no, a perfect chat application will be able to,</p>
<ol>
<li>Show the chat message to the UI right after the data gets inserted to database</li>
<li>Show the chats in multiple clients, here in our application, if you are opening the URL in multiple browser instance, and if you need to show the chats to both instances, you will have to refresh the pages right? This is not a recommended way</li>
</ol>
<p>That&#8217;s why we are going to implement Socket.io in our application.</p>
<h4>Require the package</h4>
<p>Unlike the other packages, adding socket.io to the application is a different process, we will have to require the http server first, then, set our app. You can see more information on socket.io <a href="https://socket.io/">here</a>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var http = require("http").Server(app)
var io= require("socket.io")(http)</pre>
<h4>Enabling the connection</h4>
<p>To enable the connection, we need to use the function io.on.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">io.on("connection", (socket) =&gt; {
    console.log("Socket is connected...")
})</pre>
<h4>Listen using new http server</h4>
<p>Now that we have a new http server, and we should change our listen code to our new http.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var server = http.listen(3020, () =&gt; {
    console.log("Well done, now I am listening on ", server.address().port)
})</pre>
<h4>Changes in script</h4>
<p>Let&#8217;s do listen for the event &#8220;chat&#8221; now in our html page.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var socket = io()
socket.on("chat", addChat)</pre>
<p>Please do not forget to include the socket.io.js reference in our index page, other wise you may get an error as &#8220;Uncaught ReferenceError: io is not defined&#8221;</p>
<h4>Emits the event</h4>
<p>Once the above step is completed we need to make sure we are emitting the new event on our Post API.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.post("/chats", async (req, res) =&gt; {
 try {
 var chat = new Chats(req.body)
 await chat.save()
 res.sendStatus(200)

 //Emit the event
 io.emit("chat", req.body)

 } catch (error) {
 res.sendStatus(500)
 console.error(error)
 }
})</pre>
<p>&nbsp;</p>
<p>Let&#8217;s just run our application in two browser instances and check for the output.</p>
<div id="attachment_12598" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/Socket.io-Output-e1512388473997.png"><img decoding="async" aria-describedby="caption-attachment-12598" class="size-full wp-image-12598" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/Socket.io-Output-e1512388473997.png" alt="Socket.io Output" width="634" height="596" /></a><p id="caption-attachment-12598" class="wp-caption-text">Socket.io Output</p></div>
<p>Please make sure that you are getting the chats in the second instance when you send it from the first instance of the browser and vice versa.</p>
<p>&nbsp;</p>
<h3><span id="conclusion">Conclusion</span></h3>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h3><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h3>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/creating-a-chat-application-in-node-js-with-express-mongodb-mongoose-and-socket-io/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Using MongoDB on Node JS Application Using Mongoose</title>
		<link>https://mail.sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/</link>
					<comments>https://mail.sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 03 Dec 2017 17:15:12 +0000</pubDate>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Node JS]]></category>
		<category><![CDATA[Easy way to insert data to MongoDB]]></category>
		<category><![CDATA[MongoDB with Mongoose]]></category>
		<category><![CDATA[Mongoose]]></category>
		<category><![CDATA[Node JS and MongoDB]]></category>
		<category><![CDATA[NPM]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12589</guid>

					<description><![CDATA[[toc] Introduction In this post, we are going to see how we can use a MongoDB on our Node JS application with the help of the package Mongoose. We will also be covering some facts about MongoDB so that as a reader, you will understand why we had chosen MongoDB as our backend. We will be going through some steps to install the required packages using a node package manager terminal, so please be with me. At the end of this article, I guarantee that you will be proficient on how to connect a MongoDB in our Node JS application. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>In this post, we are going to see how we can use a <a href="http://sibeeshpassion.com/category/MongoDB">MongoDB</a> on our Node JS application with the help of the package Mongoose. We will also be covering some facts about MongoDB so that as a reader, you will understand why we had chosen MongoDB as our backend. We will be going through some steps to install the required packages using a node package manager terminal, so please be with me. At the end of this article, I guarantee that you will be proficient on how to connect a MongoDB in our Node JS application. I hope you will like this article.</p>
<h3>Why MongoDB?</h3>
<p>Here, I am going to list down the reasons why I had chosen MongoDB.</p>
<ol>
<li>MongoDB is a NoSQL database when I say NoSQL, it means that it doesn&#8217;t have any structure to be followed.</li>
<li>There are no relationships, we can perform the relation using separate packages like Mongoose</li>
<li>Everything is JSON, even the data and collections are stored as JSON</li>
<li>Since the data is stored as JSON, no more conversions are needed. We can directly use it in our application.</li>
</ol>
<h3><span id="source-code">Source Code</span></h3>
<p>You can always clone or download the source code <a href="https://code.msdn.microsoft.com/Node-MongoDB-Mongoose-40fc3ad4">here</a></p>
<h3>Background</h3>
<p>Node JS has become a trend now, thus some most used databases. One of the recommended database for a Node application is MongoDB. As we discussed a MongoDB doesn&#8217;t have any structure inbuilt, here we are going to use a package called Mongoose, with that we can create some structure for our Database. Let&#8217;s just skip the talking and start developing.</p>
<h3>Setting up Node application</h3>
<p>To get started with the Node JS, create a folder and name as per your wish, this is going to be our project directory. Here I am going to use one of my favorite editor, Visual Studio Code. Now please point to your project container, and run the command below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm init</pre>
<div id="attachment_12591" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/NPM-Init.png"><img decoding="async" aria-describedby="caption-attachment-12591" class="size-full wp-image-12591" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/NPM-Init.png" alt="NPM Init" width="634" height="449" srcset="/wp-content/uploads/2017/12/NPM-Init.png 504w, /wp-content/uploads/2017/12/NPM-Init-300x212.png 300w, /wp-content/uploads/2017/12/NPM-Init-400x283.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12591" class="wp-caption-text">NPM Init</p></div>
<p>This will create a file named &#8220;Package.json&#8221; in your directory. We will be adding all of our dependencies in this file very soon. The command may ask you some default questions which you need to answer. If you need to create the package.json file with default values in it, you may consider running the below command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm init --yes</pre>
<p>Let&#8217;s review our package.json file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
  "name": "node-mongodb-mongoose",
  "version": "1.0.0",
  "description": "A Node application with MongoDB and Mongoose",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "keywords": [
    "Node",
    "Mongoose",
    "MongoDB"
  ],
  "author": "Sibeesh Venu",
  "license": "ISC"
}
</pre>
<h3>Getting the required packages</h3>
<p>Now that we have the application ready, let&#8217;s get the required packages ready.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm install --save mongoose</pre>
<p>This will create a new folder npm_modules on your project directory where you can see the package Mongoose in it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm install --save express</pre>
<p>The above command will add the package express to our application.</p>
<h3>Creating the Node App</h3>
<p>Now we can create our server.js file where we are going to write most of our application code.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var express = require("express")
var app = express()
app.listen("3010",()=&gt;{
    console.log("I just started listening!.")
})
</pre>
<p>Now run the command <code class="EnlighterJSRAW" data-enlighter-language="shell">node server.js</code>and make sure that you are getting a console as &#8221; I just started listening!.&#8221;.</p>
<p>If you are getting an error as preceding, please make sure that you are running the application on an unused port.</p>
<blockquote><p>PS F:\Visual Studio\Node.JS\Node-MongoDB-Mongoose&gt; node server.js<br />
events.js:136<br />
throw er; // Unhandled &#8216;error&#8217; event<br />
^</p>
<p>Error: listen EADDRINUSE :::3000<br />
at Object._errnoException (util.js:1031:13)<br />
at _exceptionWithHostPort (util.js:1052:20)<br />
at Server.setupListenHandle [as _listen2] (net.js:1367:14)<br />
at listenInCluster (net.js:1408:12)<br />
at Server.listen (net.js:1496:7)<br />
at Function.listen (F:\Visual Studio\Node.JS\Node-MongoDB-Mongoose\node_modules\express\lib\application.js:618:24)<br />
at Object.&lt;anonymous&gt; (F:\Visual Studio\Node.JS\Node-MongoDB-Mongoose\server.js:3:5)<br />
at Module._compile (module.js:641:30)<br />
at Object.Module._extensions..js (module.js:652:10)<br />
at Module.load (module.js:560:32)&#8221;</p></blockquote>
<h3>Setting up database</h3>
<p>Now that we have our application ready, let&#8217;s go and create our database. I am going to use mLab for creating the database. If you have not installed MongoDB on your machine, I strongly recommend creating a database in <a href="https://mlab.com/home">mLab.</a> I had created a database there and have got my connection string as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">mongodb://&lt;dbuser&gt;:&lt;dbpassword&gt;@ds038319.mlab.com:38319/mylearning</pre>
<p>We will be updating the connection string with actual DB user and password later. Please make sure that you are creating a user for your DB and remember the password.</p>
<h3>Creating a Mongoose model</h3>
<p>Let&#8217;s create a Mongoose model and set up our connection string now, which is going to be our collection. No worries, it is just a <a href="http://sibeeshpassion.com/category/JavaScript">JavaScript</a> model.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">var conString = "mongodb://admin:admin@ds038319.mlab.com:38319/mylearning"

/**
 * Models 
 */
var User = mongoose.model("User", {
    firstName: String,
    lastName: String
})</pre>
<blockquote><p>Please be noted that, when you move the codes to production, make sure that your password and user fields on the connection string are separated from this file and encrypted</p></blockquote>
<p>Now let&#8217;s connect our database.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">mongoose.connect(conString, { useMongoClient: true }, () =&gt; {
    console.log("DB is connected")
})</pre>
<h3>Setup the data</h3>
<p>We have our model ready, what else is needed now? Yes, you are right, we need data.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var dummyUser = {
    firstName: "Sibeesh",
    lastName: "Venu"
}</pre>
<h3>Inserting the data into MongoDB</h3>
<p>We have got everything ready, we can insert the model now. Let&#8217;s do the saving logic now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">mongoose.connect(conString, { useMongoClient: true }, () =&gt; {
    console.log("DB is connected")
    saveData()
})</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="js">function saveData() {
    var user = new User(dummyUser);
    user.save();
}</pre>
<h3>Verify the data</h3>
<p>Once you run your application, go to your database and check for the entries there. I am sure there will be a new collection &#8220;User&#8221; and our inserted data. As I am using mLab database, here is how my data saved.</p>
<div id="attachment_12590" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/MongoDB-Data-Insertion.png"><img decoding="async" aria-describedby="caption-attachment-12590" class="size-full wp-image-12590" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/MongoDB-Data-Insertion.png" alt="MongoDB Data Insertion" width="634" height="420" srcset="/wp-content/uploads/2017/12/MongoDB-Data-Insertion.png 539w, /wp-content/uploads/2017/12/MongoDB-Data-Insertion-300x199.png 300w, /wp-content/uploads/2017/12/MongoDB-Data-Insertion-400x265.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12590" class="wp-caption-text">MongoDB Data Insertion</p></div>
<p>If you have noticed, you can see there are an another property names &#8220;_id&#8221; in our database collection. This is a unique id generated by MongoDB for us, so no need to think about it.</p>
<h3><em>Todo</em></h3>
<p>As the purpose of this article is to show how we can insert a data to MongoDB, I called the save method right after the database is connected. In our real life, this is not a recommended way. You must create an Ajax post request and handle the same. I am leaving that task to you. Please try to do that and let me know. I would love to hear back from you.</p>
<h3><span id="conclusion">Conclusion</span></h3>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h3><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h3>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
