Tuesday, 29 November 2016

Beginner guide to Mongodb database

Beginner guide to Mongodb database

MongoDB is an open-source document database that provides high performance, high availability, and automatic SCALING. MongoDB documents are similar to JSON objects. MongoDB stores data in the form of BSON -Binary encoded JSON documents which supports a rich collection of types. Fields in BSON documents may hold arrays of values or embedded documents.

Structural aspects of MongoDB
1. Data Model
  • A record in MongoDB is a document, which is a data structure composed of field and value pairs.
  • MongoDB stores documents in collections.Collections are analogous to tables in relational databases. 
  • Documents stored in a collection must have a unique _id field that acts as a primary key. 

There are two ways to stores documents in a collection either in Normalized for or embedded into another document itself.
a) Normalized Data Models
The relationships between data is stored by links (references) from one document to another.
b) Embedded Data Models
Embedded documents store relationships between data by storing related data in a single document structure (shown below). These denormalized data models allow applications to retrieve and manipulate related data in a single database operation.
i.e. Embedded sub document
"_id" : 1,
"Employeeid" : 1001,
"EmployeeName" : "Sudhir",
"State":"Uttar Pradesh"

2. GridFS
It is a specification for storing and retrieving files.It divides a file into parts, and stores each part as a separate document. GridFS uses two collections to store files. One is chunks, and the other is metadata.

3. Sharding
Sharding or Horizontal Scaling divides the data set and distributes the data over multiple servers-shards. Each shard is an independent database and collectively shards make up a single database.

MongoDB supports sharding through sharded clusters. Process of sharing
1) Shards are used to store the data.
2) Query Routers, or mongos instances, interface with client applications and direct operations to the appropriate shard or shards and then returns results to the clients.

3) Config servers stores the cluster’s metadata. This data contains a mapping of the cluster’s data set to the shards. The query router uses this metadata to target operations to specific shards.

Installation process:
Step1: Download MongoDB .exe file and install it.
Step2: run Command Prompt and create folder inside C:Drive by using this command
md \data\db
Step3: Navigate to the bin folder where the mongod.exe file is located and run the following command in the cmd
“C:\Program Files\MongoDB\Server\3.0\bin\mongod.exe”
Step4: To connect to MongoDB, open another command prompt window and type:

“C:\Program Files\MongoDB\Server\3.0\bin\mongo.exe”.

Query execution in MongoDB

Before executing lets know naming restrictions

  1. Database Name Case Sensitivity
  2. Collection names should begin with an underscore or a letter character, and cannot:
  • contain the $.
  • be an empty string (e.g. "").
  • contain the null character.
  • begin with the system. prefix. (Reserved for internal use.)
  1. Field names cannot contain dots (i.e. .) or null characters, and they must not start with a dollar sign (i.e. $). 

Select database
Synatx: >use myDB
If a database does not exist, MongoDB creates the database

If you want to check your databases list, use the command show dbs.
Synatx: > show dbs

Drop Database
Synatx: > db.dropDatabase()
This will delete the selected database.

Adding documents using insert() command
MongoDB provides the insert () command to insert documents into a collection. It create collection if they do not already exist.
Step 1) Write the "insert" command
Step 2) Within the "insert" command, add the required Field Name and Field Value for the document which needs to be created.
Synatx: >db.Employee.insert(
"Employeeid" : 1,
"EmployeeName" : "Martin"

Explicit Creation
MongoDB provides the db.createCollection() method to explicitly create a collection with various options
Synatx: db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )
This command creates a collection named log with a maximum size of 5 megabytes and a maximum of 5000 documents.
Create a Collection with Document Validation
Synatx: >db.createCollection( "contacts",
      validator: { $or:
            { phone: { $type: "string" } },
            { email: { $regex: /@mongodb\.com$/ } },
            { status: { $in: [ "Unknown", "Incomplete" ] } }

Drop Collection
Synatx: >db.contacts.drop()
Here "contacts" is name of collection

List Record From Collection
Synatx: >db.Employee.find({});

Code Explanation:
Employee is the collection name in the MongoDB database
The find command is an in-built function which is used to retrieve the documents in the collection.

List Record in JSON Format
Synatx: >db.Employee.find().forEach(printjson);

"_id" : ObjectId("583d4378f0dd105a25b2b5cb"),
"Employeeid" : 1,
"EmployeeName" : "Sudhir"

To display the results in a formatted way, you can use pretty() method.
Synatx: >db.Employee.find().pretty();

To Return only one document use findOne().

Where Clause in MongoDB

We can also add criteria to our queries so that we can fetch documents based on certain conditions.
Synatx: >db.Employee.find({EmployeeName : "Smith"}).forEach(printjson);
Greater Than
Synatx: >db.Employee.find({Employeeid : {$gt:2}}).forEach(printjson);
Less Than
Synatx: >db.mycol.find({"likes":{$lt:50}}).pretty()
Greater Than Equals
Synatx: >db.mycol.find({"likes":{$gte:50}}).pretty()
Not Equals
Synatx: >db.mycol.find({"likes":{$ne:50}}).pretty()

  • The $gt means greater than expression.
  • The $gte means Greater Than Equals.
  • The $lt means Less Than.
  • The $ne means Not Equals.

Insert multiple documents at a time
Step 1) Create a Javascript variable called myEmployee to hold the array of documents
Step 2) Add the required documents with the Field Name and values to the variable
Step 3) Use the insert command to insert the array of documents into the collection

Synatx: >var myEmployee=

"Employeeid" : 1,
"EmployeeName" : "Sudhir"
"Employeeid: : 2,
"EmployeeName" : "Mohan"
"Employeeid: : 3,
"EmployeeName" : "Joe"
Synatx: >db.Employee.insert(myEmployee);

Synatx: >db.Employee.find().limit(2).forEach(printjson);
ByDefault limit takes ObjectId in ascending order

Update Query
Synatx: >db.Employee.update({"Employeeid":1},{$set:{"EmployeeName":"Sudhir"}});
Note: Here Employeeid is fields condition and $set is used to change the value.

Delete document from collection
Synatx: >db.mycol.remove({'title':'MongoDB Overview'})
Remove All Documents
Synatx: >db.mycol.remove()

Create User with Roles
Synatx: >use products
Synatx: >db.createUser(
user: "accountUser",
pwd: "password",
roles: [ "readWrite", "dbAdmin" ]

Create Administrative User with Roles
Synatx: >db.createUser(
user: "appAdmin",
pwd: "password",
{ role: "readWrite", db: "config" },

Drop All Users form database

Synatx: > db.runCommand( { dropAllUsersFromDatabase: 1, writeConcern: { w: "majority" } } )

Important Notes:

By default MongoDB does not support such primary key - foreign key relationships. However, we can achieve this concept by embedding one document inside another.

A replica set is a group of mongo instances that host the same data set. In replica set, one node is primary, and another is secondary. From primary to the secondary node all data replicates.

Across multiple servers, the process of synchronizing data is known as replication. It provides redundancy and increase data availability with multiple copies of data on different database server. Replication helps in protecting the database from the loss of a single server.

Journaling is the feature in MongoDB that you can use to do safe backups.

Objectld is composed of
  1. Timestamp
  2. Client machine ID
  3. Client process ID
  4. 3 byte incremented counter

Db.isMaster() will tell you whether you are on the master server or not. MongoDB allows only one master server, while couchDB allows multiple masters.

Query Conversion from mysql to MongoDB
Select field1, field2 from employee where emp_id=1;

Select * from employee where emp_id > 1 order by field2 desc limit 10,20;

Select a1,a2 from users;

Insert into users value(1,2);

Create index

Delete index

SELECT * FROM employess WHERE age > 25 AND   age <= 50
db.employess.find({age: {$gt: 25, $lte: 50}})

SELECT * FROM employess WHERE user_name like "%sudhir%"
db.employess.find({user_name: /sudhir/})

SELECT * FROM employess WHERE user_name like "sudhir%"
db.employess.find({user_name: /^sudhir/})

SELECT COUNT(*) FROM employess

SELECT COUNT(user_id) FROM employess
db.employess.count( { user_id: { $exists: true } } )
db.employess.find( { user_id: { $exists: true } } ).count()

SELECT DISTINCT(emp_name) FROM employess

EXPLAIN SELECT * FROM employess WHERE status = 1

db.employess.find({status: 1}).explain()


Post a Comment