Showing posts with label Mongo db. Show all posts
Showing posts with label Mongo db. Show all posts

Friday, February 3, 2017

Express With MongoDB - Quick start

Let's access MongoDB from Nodejs using Express. 

What is Express? 
As per Express site, it's a minimal and flexible Node.js web application framework that provides a robust set of features for the web and mobile applications.

Features
·         Robust routing
·         Focus on high performance
·         Super-high test coverage
·         HTTP helpers (redirection, caching, etc)
·         View system supporting 14+ template engines
·         Content negotiation
·         Executable for generating applications quickly

Great.Lets start. (Assumed you have Nodejs and MongoDB installed, if not ,check Nodejs MongoDb)

Create a folder and run following command on your terminal-

 > npm init

It will ask you few questions (Like- Name for the project, author, version). For now, you can keep all the default values. This will give you your package.json inside the same folder.

Greate execute this now-

> npm install --save express
mongoose morgan body-parser

So here, we actually installed Express along with mongoose which is a Node.js library that provides MongoDB object mapping similar to ORM with a familiar interface within Node.js and Morgan which is basically used for logging request details. And body-parser parses incoming request bodies in a middleware before your handlers, available under the req.body property.

Now you should see a folder named node_modules inside your current folder. Inside node_modules all your installed node packages reside. We are now ready to go further.

Let's create a file and name it server.js. Put the following code and save it.

var express = require('express'); // load express module in your project

var morgan = require('morgan'); // load morgan module 

var mongoose = require('mongoose'); //load mongoose module 

var bodyParser = require('body-parser'); // load body-parser module 

var app = express(); //init express
var port = process.env.PORT || 6064; //allocate the port for your server
app.use(express.static('./public')); // set folder for public items , such as - image , css, html, client side js
app.use(morgan('dev')); // init morgan for logging request details
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

mongoose.connect('mongodb://localhost/mongodbtest'); // mongodb connection

routesetup(app);// set your route details with path and its handlers 
app.listen(port);// start your server
console.log("App listening on port " + port); 


function routesetup(app) { // function for route setup
   app.use( function (req, res, next) {  // will be executed for all request
        console.log(req.url);
        next();
    });
    app.use( function (err, req, res, next) { // will be executed for all error
        console.log(err);
        next();
    });    
// REST API to access from client side js--> 
    app.get('/api/todos', function (req, res) { // get method route
       todo.find(function (err, todos) { // used mongoose model to get data
            if (err) {
                res.send(err);
            }

            res.json(todos);
        });
    });
app.post('/api/todos', function (req, res) { //post method route
 var td = new todo({
 val: req.body.val
        });

        td.save(function (err, td) { // use mongoose model to dave data
            if (err) {
                return res.status(500).json({
                    message: 'Error when creating todo',
                    error: err
                });
            }
            return res.status(201).json(todo);
        });
});
    app.get('*', function (req, res) { // get method for html
        //throw new Error('err');
        res.sendFile(__dirname + '/public/index.html');
    });
}

var todo = mongoose.model('Todo', { //mongoose model
    val: {
        type: String,
        default: ''
    }
});

Now create a folder public and inside it create a file index.html  and add following -

<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script>
    $(document).ready(function () {
        $("#btn").click(function () {
            $.post("/api/todos",
                {
                    val: $("#txttask").val()
                },
                function (data, status) {
                    console.log("Data: " + data + "\nStatus: " + status);
                });

            $("#txttask").val('');
            getData();
        });
        function getData() {
            $.get("/api/todos", function (data, status) {
                var listVal = "";
                $.each(data, function (index, val) {
                    listVal += val.val + "<br>";
                })
                $("#listtask").html(listVal);
            });
        }
        getData();
    });
</script>
</head>

<body>
    <div>
        <b>Express Running</b></div>
    <div>
        <label> Task:</label><input type="text" id="txttask" /><button id="btn">Save</button>
    </div>
    <div>
        <b>Task List</b>
    </div>
    <div id="listtask"></div>
</body>

</html>

Save both the files.

Note: Please read all the inline comments carefully for better understanding.

Greate . Now we are ready to run our first Express application with MongoDB.

Run you mongoDB, before going further.(go to your mongo installation folder and then ./bin folder using a new terminal window)

mongod --directoryperdb --dbpath <folder path>


To Run the application, execute following in your terminal-

> node server.js

Now Try to open - http://localhost:6064/

If you have done it properly, you should see your HTML page with heading Express Running. Using the api created in server.js you can save and see the saved list of items in the page.

That's it.

Feel free to ask if you have any queries. 



Friday, January 20, 2017

NOSQL -MongoDB

Introduction





Setup Mongo


Download & Install Mongo from- MongoDB site

Now you need a folder to store the data. So, Create one and Setup mongo.

Run MongoDB command in console-

mongod --directoryperdb --dbpath <folder path> --logpath <file path> --logappend --rest 

Mongo commands


Great, you are ready to do DB functionalities. For this, you have to run following command in the console. 

mongo

That's it. It will open a shell for executing mongo commands.

Show list of DBs-
>show DBS

Create/Use the DB-
>use local

See selected DB-
>db

Create user for db-
>db.createUser({user:"test",pwd:"1234",roles: ["readWrite","dbAdmin"]});

Create a collection in DB-
>db.createCollection('employee');

Show all collections in DB-
>show collections

Insert document in a collection-
>db.employee.insert({first_name:"sudhir", last_name:"ghosh"});

Fetch the documents-
>db.employee.find();

Insert multiple documents-
>db.employee.insert([{first_name:"sakti", last_name:"ghosh"},{first_name:"subha", last_name:"ghosh", gender:"M"}]);

Get Collection-
>db.employee.find().pretty();

Update commands -
>db.employee.update({first_name:"sakti"},{first_name:"sakti", last_name:"ghosh",gender:"M"});

>db.employee.update({first_name:"sudhir",{$set:{age: 40}});

>db.employee.update({first_name:"sudhir",{$inc:{age:5}});

>db.employee.update({first_name:"sudhir",{$unset:{age}});

>db.employee.update({first_name:"rnga"},{first_name:"ranga", last_name:"ghosh"},{upsert:true});

>db.employee.update({first_name:"rnga"},{$rename:{"gender":"m"}});

Remove commands -
>db.employee.remove({first_name:"rnga"});

>db.employee.remove({first_name:"rnga"}, {justOne:true});

Find Commands -
>db.employee.find({first_name:"sudhir"});

>db.employee.find({$or:[{first_name:"sakti"},{first_name:"sudhir"}]});

>db.employee.find({age:{$lt:40}}); //$gt/$gte/$lte

>db.employee.find({"address.city":"kol"});//json path

>db.employee.find().sort({last_name:1});//asc/desc (-1)

>db.employee.find().count();

>db.employee.find().limit(4);

>db.employee.find({deot:{$in:['software','testing']}});

>db.employee.find().forEach(function(doc){
print('name:'+ oc.first_name)});



Further study - https://docs.mongodb.com/manual/

Monday, February 17, 2014

MongoDB with MVC4 Web-API C#

Mongo db is a document oriented database. Mongo db has a free and commercial version. It is scalable, open source and document oriented. All Nosql db are document oriented mostly.  Main data base types are RDBMS, OLAP & NoSql. NoSql db are for Big data store and faster access. It is scalable. Scalable means db can be stored in commodity computers, so NoSql databases is horizontal scalable. (Hadoop).

NoSql has mainly 3 types-
1>Key-Value, 2> Tabular, 3> Document Oriented. Mongo is document oriented NoSql Db. NoSql does not have relations. It does not support complex database. But the features are there is - Fast Performance, Query-able, scalable.  In brief, NoSql is for performance, RDBMS is for functionality, though it is not cent right from all aspects.
In case of Mongo, collections are same as tables in RDBMS. Table has recorded in row. But in mongodb stores document (BSON) in collection.

Example-
{_id:”123”, name:”subhadip”,address:”agarpara”},{_id:”124”,name:”nemo”,addresses:[{address:”add1”},{address:”add2”}]}

You can see an unstructured data collection.

Now , query to extract data from collection is there in No-Sql.
Example- db.employee.find({name:”subhadip”});

Indexing is possible in MongoDB. Ad hoc queries like- search by field, regular expression can be used. Distributed database supported in mongodb. Load-balancing is a build in feature. Mongodb has file storage functions available (GridFS). Aggregation in MongoDB is possible using map reduce. Mongo db understands longitude and latitude in its own. For business logics no need to convert record to object, it is already structured as object in code.

It supports almost all popular OS (Windows, Linux, Mac, etc).

Now lets jump to code using MVC 4, C#, MongoDriver.
Create a db in mongo called company and it should have a collection -employees.[_id,Name,Address](_id will be auto generated).
Create DB Command- >use Company (enter)
Create Collection Command->  db.Employees.insert({Name:'Subha',Address:'agarpara;}) (enter)

Install MongoC#Driver from Add Libary Package Reference
Ok, Lets start coding.
First , Create Model-
    public class Employee
    {
        [ScaffoldColumn(false)]
        [BsonId]
        public ObjectId EmpId { get; set; }

        [ScaffoldColumn(false)]
        public string Name { get; set; }

        [ScaffoldColumn(false)]
        public string Address { get; set; }
    }

Now , Create MongoDBContext-
public class MongoDBCS
    {
        public MongoDatabase db;
        public MongoDBCS()
        {
            var con =
                new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDBString"].ConnectionString);

            var server = MongoServer.Create(con);
             db = server.GetDatabase(con.DatabaseName);
        }

        public MongoCollection<Employee> Employees
        {
            get
            {
                return db.GetCollection<Employee>("Employees");
            }
            set { }
        }

    }

Now, Create controller(API)-
public class EmployeeController : ApiController
    {
        private MongoDBCS MongoContext;

        public  EmployeeController()
        {
            MongoContext = new MongoDBCS();
        }
        // GET api/employee
        public IEnumerable<Employee> Get()
        {
         
            var el = MongoContext.Employees;
            return el.FindAll();
        }

     

        // POST api/employee
        public void Post(Employee emp)
        {
            var el = MongoContext.Employees;
            el.Save(emp);
        }


        // DELETE api/employee/5
        public void Delete(string name)
        {
            var el = MongoContext.Employees;
            el.Remove(Query.EQ("Name", name));
        }
    
    }

Web.config will have db connection string –
<add name="MongoDBString" connectionString="server=127.0.0.1;database=company" />

That’s it.Now, You know how to work with MongoDB and C# MVC4.