index / key: MongoDB

Lets look at some basics of indexes in MongoDB.

If we have 3 fields in a document – name, age, sex
We could make name or age or sex or (name, age) or (name, age, sex) as index.

index-key-mongodb

Assume that we make a index out of (name, age, sex)
In this case, we need to use the keys from left to right.

If we use “name” in our command, it makes use of the index.
If we use (“name”, “age”) in our command, it makes use of the index.
If we use (“name”, “age”, “sex”) in our command, it makes use of the index.

If we use “age” in our command, it can’t use the index for its operation.
If we use (“age”, “sex”) in our command, it can’t use the index for its operation.

If we use (“name”, “sex”) in our command, it simply uses “name” field and ignores “sex” field.

indexes / keys: MongoDB


[youtube https://www.youtube.com/watch?v=NiP-zX-jPaY]

YouTube Link: https://www.youtube.com/watch?v=NiP-zX-jPaY [Watch the Video In Full Screen.]



For convenience, mongoDB adds “_id” field to each document inserted. “_id” is unique across the collection. And index is automatically created on “_id”.

Since index information is stored in “system.indexes” collection – it consumes disk too. So we need to make sure to add indexes to only those fields which we access frequently. Also note that, each time a document is inserted, “system.indexes” collection must be updated with the new index information, which takes time, bandwidth and disk space. So we need to be careful while creating indexes.

Save data To MongoDB: Node.js

After learning to connect our Node.js application to MongoDB, lets see how we could insert data into our database collection.

insert-into-mongoDB-nodejs

Note:
Save() is a higher lever method. It checks to see if the object we’re inserting is already present in our collection, by checking the _id value we’re inserting. _id field(which is a primary key in MongoDB document)
– If there is no matching _id field in a document, it’ll call insert method and insert the data. And if the data being entered has no _id value, insert() method will create _id value for us, and insert the data into the collection.
– If _id matches to any document in our collection, it’ll use update() instead to update the previously present data with the new data entered by the user.

Form To Facilitate User To Enter Her Details ..or Registration Form
public/index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< !DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
 <form action="/new" method="POST">
<label for="email">Email: </label>
  <input type="email" name="email" /><br />
<label for="name">Name: </label>
  <input type="text" name="name" /><br />
<label for="age">Age: </label>
  <input type="number" name="age" /><br />
 <input type="submit"/>
</form>
</body>
</html>

Here we have 3 input fields(for email, name and age) and a submit button. Since we’re posting these data to /new (in the action field of the form), we need to create /new route.

Route To Process User Entries
app.js

1
2
3
4
5
6
7
8
9
10
app.post('/new', function(req, res){
new user({
_id    : req.body.email,
name: req.body.name,
age   : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else    res.send('Successfully inserted!');
});
});

By using bodyParser() middleware, we get the data from the form, parse it and assign the values to corresponding keys, by creating a new user.

Note: user is a model object in our example. We also chain save method with new user object. Save() method takes a callback method as argument. The callback method takes 2 arguments – error and document. We check, if there are any errors while inserting the data, if so, we output the error object on to the screen. If the insertion was successful, we display “Successfully inserted!” message.

Inserting data To MongoDB: Node.js


[youtube https://www.youtube.com/watch?v=uZqwHfNIf8M]

YouTube Link: https://www.youtube.com/watch?v=uZqwHfNIf8M [Watch the Video In Full Screen.]



Related Read:
number Input Type: HTML5
Create and Insert Documents: MongoDB
MongoDB Tutorial List

Full Code
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
 
var app = express();
 
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
 
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
 
mongoose.connect('mongodb://localhost/Company');
 
var Schema = new mongoose.Schema({
_id    : String,
name: String,
age   : Number
});
 
var user = mongoose.model('emp', Schema);
 
app.post('/new', function(req, res){
new user({
_id    : req.body.email,
name: req.body.name,
age   : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else    res.send('Successfully inserted!');
});
});
 
 
 
var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Here we’ve shown the configurations, middleware, mongoose connection, schema, model object, routes and out application server.

Connecting To MongoDB Using Mongoose: Node.js

In today’s video tutorial lets learn to connect to MongoDB server from our Node.js application using Mongoose module.

node-mongoose-mongoDB

Mongoose Module
Mongoose provides a straight-forward, schema-based solution to modeling your application data and includes built-in type casting, validation, query building, business logic hooks and more..

MongoDB
MongoDB is one of the leading NoSQL database. Know more about it at MongoDB – Getting Started Guide

Related Read: MongoDB Tutorial List

Listing Mongoose As A Dependency
package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "nodemon app.js"
  },
  "dependencies": {
"express": "*",
"nodemon": "*",
"mongoose": "*"
  }
}

list the mongoose module as a dependency for your Node.js application

Install the dependencies

1
npm install

This looks for all the dependencies listed in package.json file and installs it. Make sure that your system is connected to the internet.

Connecting to MongoDB
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var mongoose = require('mongoose');
 
app.use(express.bodyParser());
app.use(express.methodOverride());
 
mongoose.connect('mongodb://localhost/Company');
 
var mySchema = new mongoose.Schema({
_id    : String,
name: String,
age   : Number
});
 
var user = mongoose.model('emp', mySchema);

We have to first include mongoose module into our application. We also need the help of bodyParser() and methodOverride() middlewares in order to parse the form variables and override method to make PUT and DELETE methods work.

Next we connect to mongobd using connect method of mongoose module. Here we also specify the mongoDB database name to which our application will be connecting to. If the database is not already present, this will create one for us.

Next, we write a schema definition for our collection. Mongoose uses schema for validation of user entered data. By specifying the data type for our field we can make sure user entries are validated against the data types we have mentioned in our schema.

Some valid Schema Types, supported by Mongoose
String
Number
Date
Buffer
Boolean
Mixed
Objectid
Array

Mongoose Model
A model in mongoose is an object that gives us easy access to a named collection, allowing us to query the collection and use the schema to validate any document we save to that collection.

Connecting To MongoDB Using Mongoose: Node.js


[youtube https://www.youtube.com/watch?v=93APwwh35PA]

YouTube Link: https://www.youtube.com/watch?v=93APwwh35PA [Watch the Video In Full Screen.]



Note 1: In above example code, we are creating a collection called emp and binding it with the schema mySchema

In above example
Database name: Company
Collection/table name: emp

Note 2: Make sure MongoDB server is up and running, before you execute your Node.js application.

Checking If your application succesfully connected to MongoDB Server!
app.js

1
2
3
4
5
var db = mongoose.connection('mongodb://localhost/Company');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  // all your database operations(CRUD) here 
});

Here by using on method we check if we could successfully connect to our mongoDB server. If there was any error, we output the error on to the screen. If the connection is successful, we’ll continue with our CRUD operations on the database tables.

Create and Insert Documents: MongoDB

In this video tutorial, we’ll look at the basic differences between MongoDB and traditional Database Management Systems. Also, commands to create database, collection, documents – insertion.

Topic of discussion:
Key differences.
Keyword differences.
Schema-free collection.
Database creation.
Creation of Collection.
Insertion of Documents.
JavaScript Console/Shall.

Some Commands

Show Database Already Present

1
show dbs

Create Database

1
use company

In MongoDB, it’ll never actually create any database or collection until we start storing documents in it!

Point object ‘db’ to our new database, by switching to company database

1
2
3
4
>use company
Switched to db company 
>db
company

Naming our Collection

1
db.info

So our collection name is info

Number of documents present

1
db.info.count()

using count() method, we check the no of documents present inside info collection.

Inserting document into Collection

1
2
3
4
5
db.info.insert({
 name     : 'Apple',
 product  : 'iPhone5S',
 emp_no   : 100
});

This inserts our first record.
insert() is the method, which accepts key-value pair object as it’s parameter.

JavaScript Shall
Since, this is a JavaScript shall, we can write any valid JavaScript code and interact directly with MongoDB.

Lets see another method to insert documents into the same collection.

Using save method

1
2
3
4
5
6
7
8
9
>var data = {}
>data.name = 'Technotip IT Solutions'
>data.product = 'Video Tutorials - Educational'
>data.emp = [ 'Satish', 'Kiran' ]
>data.videos = {}
>data.videos.mongo = 'MongoDB videos'
>data.videos.php = 'PHP Video Tutorials'
 
>db.info.save(data);

We create a JSON object data.
We start storing { key: value } pair into it.
emp is an array, which contains name of 2 employees.
videos is a sub object.

Now using save method we insert this data object into info collection.

Save()
Save() is a higher lever method. It checks to see if the object we’re inserting is already present in our collection, by checking the _id value we’re inserting. _id field(which is a primary key in MongoDB document)
– If there is no matching _id field in a document, it’ll call insert method and insert the data. And if the data being entered has no _id value, insert() method will create _id value for us, and insert the data into the collection.
– If _id matches to any document in our collection, it’ll use update() instead to update the previously present data with the new data entered by the user.

Database, Collections, Documents: MongoDB


[youtube https://www.youtube.com/watch?v=yAjG_fC6fPU]

YouTube Link: https://www.youtube.com/watch?v=yAjG_fC6fPU [Watch the Video In Full Screen.]



Note:
There is no Schema for our collection. i.e., no column name and datatype.
Since documents are in BSON format, insertion and finding data is much faster.

Schema-free design is flexible and is of much use in modern day web application.

Example: Users upload photos and tag names of people in the pic. This can be stored as an array of tags in a key value pair, for only those pics which has tags. For other pics, we need not create this array itself. This is flexible. Also BSON format helps create application with high Scalability.