Using MongoDB with NodeJS

http://blog.modulus.io/mongodb-tutorial

Install modules:
npm install mongodb –save
npm install assert –save

var MongoClient = require('mongodb').MongoClient,
assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/conFusion';

// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {

    assert.equal(err,null);
    console.log("Connected correctly to server");
	
	var collection = db.collection("dishes");
	collection.insertOne({name: "Uthapizza", description: "test"}, function(err,result){
		assert.equal(err,null);
		console.log("After Insert:");
		console.log(result.ops);
			collection.find({}).toArray(function(err,docs){
				assert.equal(err,null);
				console.log("Found:");
				console.log(docs);
				db.dropCollection("dishes", function(err, result){
				   assert.equal(err,null);
				   db.close();
				});
			});
	});
});

Advertisements

MongoDB Concepts

Basics of MongoDB:

Database:
Is a physical container for collections.
Each database gets its own set of files on the file system.
A single MongoDB server typically has multiple databases.

Collection:
Is a group of MongoDB documents.
It is the equivalent of an RDBMS table.
A collection exists within a single database.
Collections do not enforce a schema.
Documents within a collection can have different fields.
Typically, all documents in a collection are of similar or related purpose.

Document:
Is effectively a JSON document with some additional features.
Is a set of key-value pairs.
Documents have dynamic schema.
Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.

MongoDB stores the documents in BSON (Binary JSON) format
– Supports length prefix on each value (Easy to skip over a field)
– Information about the type of a field value
– Additional primitives types not suppported by raw JSON like UTC date time, raw binary, and ObjectId


The data structure that defines a MongoDB document is called BSON (Binary JSON).
BSON is binary representation of JSON and also supports data types such as Date, which is not supported in plain JSON format.

MongoDB internally converts JSON to BSON and vice versa for performance benefits, although the user can save, query and retrieve as JSON.

MongoDB ObjectId
• Every document in Mongo must have an “_id” field that is unique
• Default ObjectId created by Mongo when you insert a document
• Example:
{
“_id” : ObjectId(“56ce74c0b02806eff4558f1f”),
“name” : “Uthapizza”,
“description” : “Test”
}

ObjectId is a 12 byte field:
• id.getTimestamp() returns the timestamp in ISO Date format.

var id = new ObjectId();
id.getTimestamp();

MongoDB Useful Commands

1) db.stats()
2) db.help()

Databases:
Create a new database: use name_of_db
Show all existing database: show dbs
Drop currently selected database: db.dropDatabase()
Insert in a database: db.name_of_db.insert(“name”:”abc”)

Collections:
To create a collection: db.createCollection(name, options)
In mongodb you don’t need to create collection. MongoDB creates collection automatically, when you insert some document.

Drop a collection: db.COLLECTION_NAME.drop()

Documents:
Insert Document:
we can insert a document with a insert or save command.
db.COLLECTION_NAME.insert(document)
db.COLLECTION_NAME.save(document)
If collection does not exist a new one is created.

Query Document: To query data from MongoDB collection, you need to use MongoDB’s find() method.
db.COLLECTION_NAME.find()

To get results in formatted way: db.mycol.find().pretty()
To get a single result in output file: db.mycol.findOne()

OR Query:
db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()

AND Query:
db.mycol.find({key1:value1, key2:value2}).pretty()


Update Document:
with update() and save() method
With update() method:
db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

With save() method:
db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

Remove Document:
db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Remove only one document:
db.COLLECTION_NAME.remove(DELETION_CRITERIA, 1)

Remove all documents:
db.COLLECTION_NAME.remove()

 

Query Projection:
db.COLLECTION_NAME.find({},{KEY:1})

 

Limit the records:
db.COLLECTION_NAME.find().limit(NUMBER)

Skip the documents:
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

 

Sort the documents: 1 is used for ascending order while -1 is used for descending order.
db.COLLECTION_NAME.find().sort({KEY:1})

MongoDB Getting Started

To install mongodb on windows: https://code.msdn.microsoft.com/Mongo-Database-setup-on-6963f46f

Steps:
1) download the windows installer from mongodb.
2) install the msi file.
3) setup the path environment variable to the bin directory of the installation of mongodb.
4) run the command:

mongod --dbpath PATH_TO_DIRECTORY_WHERE_YOU_WANT_DB

Mongodb server will start waiting for a connection.
5) Now in an another cmd prompt:

mongo
db.test.save({ a: 1 })
db.test.find()

Now we have inserted values in the db.