Coding Cheatsheets - Learn web development code and tutorials for Software developers which will helps you in project. Get help on JavaScript, PHP, XML, and more.

Post Page Advertisement [Top]

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
Example:
{
"_id" : 1,
"Employeeid" : 1001,
"EmployeeName" : "Sudhir",
"Contact":{
"phone":9711969920,
"email":"shidhu047@gmail.com"
},
"Address":{
"City":"Noida",
"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
Example:
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);
Output:

{
"_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()

Note: 
  • 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);

Limits
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",
roles:
[
{ role: "readWrite", db: "config" },
"clusterAdmin"
]
}
)

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
Example1:
Select field1, field2 from employee where emp_id=1;
As
db.employee.find({emp_id:1},{field1:1,field2:1});

Example2:
Select * from employee where emp_id > 1 order by field2 desc limit 10,20;
As
db.employee.find({emp_id:{&gt:1}}).sort(field2:-1).skip(10).limit(20);

Example3:
Select a1,a2 from users;
As
db.users.find({},{a1:1,a2:1});

Example4:
Insert into users value(1,2);
As
db.users.insert({a1:1,a2:2});

Create index
db.users.ensureIndex({"title:1"});

Delete index
db.users.dropIndex({"title:1"});

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

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

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

Example8:
SELECT COUNT(*) FROM employess
db.employess.count()

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

Example10:
SELECT DISTINCT(emp_name) FROM employess
db.employess.distinct("emp_name")

Example11:
EXPLAIN SELECT * FROM employess WHERE status = 1

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

1 comment:

  1. One of the first reasons for adopting automated CNC CNC machining machines is to deal with the shortage of skilled laborers challenges that almost all} industries are at present facing. This permits manufacturing industries to extend their effectivity and maximize the production output. To tackle this demand, incumbents in this area, similar to Fanuc Corporation and OKAMA America Corporation, emphasize integrating new technologies with the prevailing product portfolio. CNC stands for “computer numerical control” and CNC machining refers to a machining process where instruments are managed by specific directions by way of a pc program.

    ReplyDelete

Bottom Ad [Post Page]