Mysql PDF
Mysql PDF
The NoSQL style databases has often been termed non-relational databases.
This is an unfortunate term. These databases can certainly be used with data
that has relations, which is actually extremely important. In fact, real data
almost always has relations. Truly non-relational data management would be
virtually worthless. Understanding how to deal with relations has not always
been well-addressed by NoSQL discussions and is perhaps one of the most
important issues for real application development on top of NoSQL
databases.
Schemas/Validation
One aspect of the NoSQL movement has been a move away from trying to
maintain completely perfect consistency across distributed servers (everyone
has the same view of data) due to the burden this places on databases,
particularly in distributed systems. The now famous CAP theorem states that
of consistency, availability, and network partitioning, only two can be
guaranteed at any time. Traditional relational databases have kept strict
transactional semantics to preserve consistency, but many NoSQL databases
are moving towards a more scalable architecture that relaxes consistency.
Relaxing consistency is often called eventual consistency. This permits much
more scalable distributed storage systems where writes can occur without
using two phase commits or system-wide locks.
Persevere
Create Operations
Create or insert operations add
new documents to a collection. If the
collection does not currently exist, insert
operations will create the collection.
db.collection.insertOne() inserts
a single document into a collection.
The following example inserts a new
document into the inventory collection. If
the document does not specify an _id field,
MongoDB adds the _id field with an
ObjectId value to the new document.
See Insert Behavior.
copy
copied
db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h:
28, w: 35.5, uom: "cm" } }
)
Read Operations
Read operations retrieves documents from
a collection; i.e. queries a collection for
documents. MongoDB provides the
following methods to read documents from
a collection:
∙ db.collection.find()
Query Operators
A query filter document can use the query
operators to specify conditions in the
following form:
{ <field1>: { <operator1>: <value1> }, ... }
Specify AND Conditions
A compound query can specify conditions
for more than one field in the collection’s
documents. Implicitly, a
logical AND conjunction connects the
clauses of a compound query so that the
query selects the documents in the
collection that match all the conditions.
copy
copied
db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30
}}]})
The operation corresponds to the following SQL statement:
copy
copied
∙ db.collection.find() method in
the mongo shell. The examples on this
page use the inventorycollection. To
populate the inventory collection, run the
following:
∙ copy
∙ copied
∙ db.inventory.insertMany( [
∙ { item: "journal", qty: 25, size: { h: 14, w: 21, uo
m: "cm" }, status: "A" },
∙ { item: "notebook", qty: 50, size: { h: 8.5, w: 11,
uom: "in" }, status: "A" },
∙ { item: "paper", qty: 100, size: { h: 8.5, w: 11, uo
m: "in" }, status: "D" },
∙ { item: "planner", qty: 75, size: { h: 22.85, w: 30,
uom: "cm" }, status: "D" },
∙ { item: "postcard", qty: 45, size: { h: 10, w: 15.2
5, uom: "cm" }, status: "A" }
∙ ]);
∙ Match an
Embedded/Nested
Document
∙ To specify an equality condition on a
field that is an embedded/nested
document, use the query filter
document {<field>: <value> } where <valu
e> is the document to match.
∙ copied
∙ copied
∙ copied
∙ Specify AND Condition
∙ copied
∙ Query an Array
∙ copied
∙ db.inventory.insertMany([
∙ { item: "journal", qty: 25, tags: ["blan
k", "red"], dim_cm: [ 14, 21 ] },
∙ { item: "notebook", qty: 50, tags: ["red", "bla
nk"], dim_cm: [ 14, 21 ] },
∙ { item: "paper", qty: 100, tags: ["red", "blank
", "plain"], dim_cm: [ 14, 21 ] },
∙ { item: "planner", qty: 75, tags: ["blank", "red"], di
m_cm: [ 22.85, 30 ] },
∙ { item: "postcard", qty: 45, tags: ["blue"], dim_c
m: [ 10, 15.25 ] }
∙ ]);
∙ You can run the operation in the web
shell below:
∙ Match an Array
∙ To specify equality condition on an
array, use the query
document { <field>: <value> } where <val
ue> is the exact array to match,
including the order of the elements.
∙ copied
∙ copied
∙ copied
∙ copied
∙ copied
∙ Use $elemMatch operator to specify
multiple criteria on the elements of an
array such that at least one array
element satisfies all the specified
criteria.
∙ copied
∙ copied
∙ copied
∙ copied
∙ db.inventory.insertMany( [
∙ { item: "journal", instock: [ { warehouse: "A", qty:
5 }, { warehouse: "C", qty: 15 } ] },
∙ { item: "notebook", instock: [ { warehouse: "C",
qty: 5 } ] },
∙ { item: "paper", instock: [ { warehouse: "A", qty:
60 }, { warehouse: "B", qty: 15 } ] },
∙ { item: "planner", instock: [ { warehouse: "A", qt
y: 40 }, { warehouse: "B", qty: 5 } ] },
∙ { item: "postcard", instock: [ { warehouse: "B", q
ty: 15 }, { warehouse: "C", qty: 35 } ] }
∙ ]);
∙
∙
∙ copied
∙
∙
∙ copied
∙ copied
∙ db.inventory.find( { 'instock.qty': { $lte: 20 } } )
∙ Specify Multiple
Conditions for Array of
Documents
∙ When specifying conditions on more
than one field nested in an array of
documents, you can specify the query
such that either a single document
meets these condition or any
combination of documents (including a
single document) in the array meets the
conditions.
∙ A Single Nested Document Meets Multiple
Query Conditions on Nested Fields
∙ Use $elemMatch operator to specify
multiple criteria on an array of
embedded documents such that at least
one embedded document satisfies all
the specified criteria.
Update Operations
Update operations modify
existing documents in a collection.
MongoDB provides the following methods
to update documents of a collection:
∙ db.collection.updateOne()
∙ db.collection.updateMany()
∙ db.collection.replaceOne()
∙ db.collection.updateOne(<filter>, <update>,
<options>)
∙ db.collection.updateMany(<filter>, <update>,
<options>)
∙ db.collection.replaceOne(<filter>, <update>,
<options>)
The examples on this page use
the inventory collection. To create and/or
populate the inventory collection, run the
following:
db.inventory.insertMany( [
{ item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom:
"cm" }, status: "A" },
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "c
m" }, status: "A" },
{ item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "c
m" }, status: "A" },
{ item: "mousepad", qty: 25, size: { h: 19, w: 22.85, u
om: "cm" }, status: "P" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom:
"in" }, status: "P" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "i
n" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uo
m: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uo
m: "cm" }, status: "A" },
{ item: "sketchbook", qty: 80, size: { h: 14, w: 21, uo
m: "cm" }, status: "A" },
{ item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.
5, uom: "cm" }, status: "A" }
] );
Update Documents in a
Collection
To update a document, MongoDB
provides update operators, such as $set, to
modify field values.
db.inventory.updateOne(
{ item: "paper" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)
Replace a Document
To replace the entire content of a document
except for the _id field, pass an entirely new
document as the second argument
to db.collection.replaceOne().
Behavior
Atomicity
If updateOne(), updateMany(),
or replaceOne() includes upsert : true and n
o documents match the specified filter,
then the operation creates a new document
and inserts it. If there are matching
documents, then the operation modifies or
replaces the matching document or
documents.
For details on the new document created,
see the individual reference pages for the
methods.
Delete Operations
Delete operations remove documents from
a collection. MongoDB provides the
following methods to delete documents of
a collection:
∙ db.collection.deleteOne() New in version 3.2
∙ db.collection.deleteMany() New in version
3.2
Example
If you want to use a database with
name <mydb>, then use
DATABASEstatement would be as follows
−
>use mydb
switched to db mydb
To check your currently selected database,
use the command db
>db
mydb
If you want to check your databases list,
use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
Your created database (mydb) is not
present in list. To display database, you
need to insert at least one document into it.
>db.movie.insert({"name":"tutorials point"})
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
The dropDatabase()
Method
MongoDB db.dropDatabase() command is
used to drop a existing database.
Syntax
Basic syntax of dropDatabase() command
is as follows −
db.dropDatabase()
This will delete the selected database. If
you have not selected any database, then it
will delete default 'test' database.
Example
First, check the list of available databases
by using the command, show dbs.
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>
switched to db mydb
>db.dropDatabase()
>
local 0.78125GB
test 0.23012GB
>
The createCollection()
Method
MongoDB db.createCollection(name,
options) is used to create collection.
Syntax
Basic syntax
of createCollection() command is as
follows −
db.createCollection(name, options)
In the command, name is name of
collection to be created. Options is a
document and is used to specify
configuration of collection.
Parameter Type Description
Name String Name of the
collection to be
created
(Optional) If true,
enables a capped
capped Boolean collection. Capped
collection is a fixed size
collection that
automatically
overwrites its oldest
entries when it reaches
its maximum size. If
you specify true, you
need to specify size
parameter also.
(Optional) If true,
automatically create
autoIndexId Boolean
index on _id field.s
Default value is false.
(Optional) Specifies a
maximum size in bytes
for a capped
size number
collection. If capped is
true, then you need to
specify this field also.
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>
system.indexes
{ "ok" : 1 }
>
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
Example
First, check the available collections into
your database mydb.
>use mydb
switched to db mydb
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
true
>
mycol
system.indexes
tutorialspoint
>
∙ Example
∙ >db.mycol.insert({
∙ _id: ObjectId(7df78ad8902c),
∙ url: 'http://www.tutorialspoint.com',
∙ likes: 100
∙ })
∙ {
∙ url: 'http://www.tutorialspoint.com',
∙ likes: 100
∙ },
∙
∙ {
∙ url: 'http://www.tutorialspoint.com',
∙ likes: 20,
∙ comments: [
∙ {
∙ user:'user1',
∙ like: 0
∙ }
∙ ]
∙ }
∙ ])
Example
>db.mycol.find().pretty()
"_id": ObjectId(7df78ad8902c),
"likes": "100"
>
AND in MongoDB
Syntax
In the find() method, if you pass multiple
keys by separating them by ',' then
MongoDB treats it as AND condition.
Following is the basic syntax of AND −
>db.mycol.find(
{
$and: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
Following example will show all the
tutorials written by 'tutorials point' and
whose title is 'MongoDB Overview'.
>db.mycol.find({$and:[{"by":"tutorials point"},{"title":
"MongoDB Overview"}]}).pretty() {
"_id": ObjectId(7df78ad8902c),
"url": "http://www.tutorialspoint.com",
"likes": "100"
}
OR in MongoDB
Syntax
To query documents based on the OR
condition, you need to use $orkeyword.
Following is the basic syntax of OR −
>db.mycol.find(
$or: [
]
}
).pretty()
Example
Following example will show all the
tutorials written by 'tutorials point' or
whose title is 'MongoDB Overview'.
>db.mycol.find({$or:[{"by":"tutorials point"},{"title":
"MongoDB Overview"}]}).pretty()
"_id": ObjectId(7df78ad8902c),
"url": "http://www.tutorialspoint.com",
"likes": "100"
}
>
{
"_id": ObjectId(7df78ad8902c),
"url": "http://www.tutorialspoint.com",
"likes": "100"
>
MongoDB's update() and save() methods
are used to update document into a
collection. The update() method updates
the values in the existing document while
the save() method replaces the existing
document with the document passed in
save() method.
MongoDB Update()
Method
The update() method updates the values in
the existing document.
Syntax
The basic syntax of update() method is as
follows −
>db.COLLECTION_NAME.update(SELECTION_CRITERIA,
UPDATED_DATA)
Example
Consider the mycol collection has the
following data.
{ "_id" : ObjectId(5983548781331adf45ec5),
"title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6),
"title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7),
"title":"Tutorials Point Overview"}
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5),
"title":"New MongoDB Tutorial"}
{ "_id" : ObjectId(5983548781331adf45ec6),
"title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7),
"title":"Tutorials Point Overview"}
>
MongoDB Save()
Method
The save() method replaces the existing
document with the new document passed
in the save() method.
Syntax
The basic syntax of
MongoDB save() method is shown below −
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DAT
A})
Example
Following example will replace the
document with the _id
'5983548781331adf45ec5'.
>db.mycol.save(
"_id" : ObjectId(5983548781331adf45ec7),
"title":"Tutorials Point New Topic",
"by":"Tutorials Point"
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5),
"title":"Tutorials Point New Topic",
"by":"Tutorials Point"}
{ "_id" : ObjectId(5983548781331adf45ec6),
"title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7),
"title":"Tutorials Point Overview"}
>
The remove() Method
MongoDB's remove() method is used to
remove a document from the collection.
remove() method accepts two parameters.
One is deletion criteria and second is
justOne flag.
∙ deletion criteria − (Optional) deletion criteria
according to documents will be removed.
∙ justOne − (Optional) if set to true or 1, then
remove only one document.
Syntax
Basic syntax of remove() method is as
follows −
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Example
Consider the mycol collection has the
following data.
{ "_id" : ObjectId(5983548781331adf45ec5),
"title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6),
"title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7),
"title":"Tutorials Point Overview"}
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec6),
"title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7),
"title":"Tutorials Point Overview"}
>
Remove All
Documents
If you don't specify deletion criteria, then
MongoDB will delete whole documents
from the collection. This is equivalent of
SQL's truncate command.
>db.mycol.remove()
>db.mycol.find()
>
{ "_id" : ObjectId(5983548781331adf45ec6),
"title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7),
"title":"Tutorials Point Overview"}
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
>
Please note _id field is always displayed
while executing find() method, if you don't
want this field, then you need to set it as 0.
Example
Consider the collection myycol has the
following data.
{ "_id" : ObjectId(5983548781331adf45ec5),
"title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6),
"title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7),
"title":"Tutorials Point Overview"}
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
>
MongoDB Skip()
Method
Apart from limit() method, there is one
more method skip() which also accepts
number type argument and is used to skip
the number of documents.
Syntax
The basic syntax of skip() method is as
follows −
>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMB
ER)
Example
Following example will display only the
second document.
>db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL Overview"}
>
Example
Consider the collection myycol has the
following data.
{ "_id" : ObjectId(5983548781331adf45ec5),
"title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6),
"title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7),
"title":"Tutorials Point Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>
The ensureIndex()
Method
To create an index you need to use
ensureIndex() method of MongoDB.
Syntax
The basic syntax of ensureIndex() method
is as follows().
>db.COLLECTION_NAME.ensureIndex({KEY:1})
>
>
Creates a
unique index so
that the
unique Boolean collection will
not accept
insertion of
documents
where the index
key or keys
match an
existing value
in the index.
Specify true to
create a unique
index. The
default value
is false.
The name of
the index. If
unspecified,
MongoDB
generates an
name string index name by
concatenating
the names of
the indexed
fields and the
sort order.
Creates a
unique index on
a field that may
have
duplicates.
MongoDB
indexes only
the first
occurrence of a
key and
dropDups Boolean removes all
documents
from the
collection that
contain
subsequent
occurrences of
that key.
Specify true to
create unique
index. The
default value
is false.
If true, the
index only
references
documents
with the
specified field.
These indexes
use less space
sparse Boolean
but behave
differently in
some
situations
(particularly
sorts). The
default value
is false.
The index
version
number. The
default index
version
index
v depends on the
version
version of
MongoDB
running when
creating the
index.
The weight is a
number ranging
from 1 to
99,999 and
denotes the
weights document significance of
the field
relative to the
other indexed
fields in terms
of the score.
The aggregate()
Method
For the aggregation in MongoDB, you
should use aggregate() method.
Syntax
Basic syntax of aggregate() method is as
follows −
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERA
TION)
Example
In the collection you have the following
data −
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
url: 'http://www.tutorialspoint.com',
likes: 100
},
_id: ObjectId(7df78ad8902d)
url: 'http://www.tutorialspoint.com',
likes: 10
},
_id: ObjectId(7df78ad8902e)
by_user: 'Neo4j',
url: 'http://www.neo4j.com',
likes: 750
},
"result" : [
"num_tutorial" : 2
},
"_id" : "Neo4j",
"num_tutorial" : 1
],
"ok" : 1
>
Pipeline Concept
In UNIX command, shell pipeline means the
possibility to execute an operation on
some input and use the output as the input
for the next command and so on.
MongoDB also supports same concept in
aggregation framework. There is a set of
possible stages and each of those is taken
as a set of documents as an input and
produces a resulting set of documents (or
the final resulting JSON document at the
end of the pipeline). This can then in turn
be used for the next stage and so on.
Following are the possible stages in
aggregation framework −
∙ $project − Used to select some specific fields
from a collection.
∙ $match − This is a filtering operation and thus
this can reduce the amount of documents that
are given as input to the next stage.
∙ $group − This does the actual aggregation as
discussed above.
∙ $sort − Sorts the documents.
∙ $skip − With this, it is possible to skip forward in
the list of documents for a given amount of
documents.
∙ $limit − This limits the amount of documents to
look at, by the given number starting from the
current positions.
∙ $unwind − This is used to unwind document
that are using arrays. When using an array, the
data is kind of pre-joined and this operation will
be undone with this to have individual
documents again. Thus with this stage we will
increase the amount of documents for the next
stage.
Replication is the process of synchronizing
data across multiple servers. Replication
provides redundancy and increases data
availability with multiple copies of data on
different database servers. Replication
protects a database from the loss of a
single server. Replication also allows you to
recover from hardware failure and service
interruptions. With additional copies of the
data, you can dedicate one to disaster
recovery, reporting, or backup.
Why Replication?
∙ To keep your data safe
∙ High (24*7) availability of data
∙ Disaster recovery
∙ No downtime for maintenance (like backups,
index rebuilds, compaction)
∙ Read scaling (extra copies to read from)
∙ Replica set is transparent to the application
How Replication
Works in MongoDB
MongoDB achieves replication by the use
of replica set. A replica set is a group
of mongod instances that host the same
data set. In a replica, one node is primary
node that receives all write operations. All
other instances, such as secondaries, apply
operations from the primary so that they
have the same data set. Replica set can
have only one primary node.
∙ Replica set is a group of two or more nodes
(generally minimum 3 nodes are required).
∙ In a replica set, one node is primary node and
remaining nodes are secondary.
∙ All data replicates from primary to secondary
node.
∙ At the time of automatic failover or
maintenance, election establishes for primary
and a new primary node is elected.
∙ After the recovery of failed node, it again join the
replica set and works as a secondary node.
A typical diagram of MongoDB replication
is shown in which client application always
interact with the primary node and the
primary node then replicates the data to
the secondary nodes.
Replica Set Features
∙ A cluster of N nodes
∙ Any one node can be primary
∙ All write operations go to primary
∙ Automatic failover
∙ Automatic recovery
∙ Consensus election of primary
Example
mongod --port 27017 --dbpath "D:\set
up\mongodb\data" --replSet rs0
∙ It will start a mongod instance with the name
rs0, on port 27017.
∙ Now start the command prompt and connect to
this mongod instance.
∙ In Mongo client, issue the
command rs.initiate() to initiate a new replica
set.
∙ To check the replica set configuration, issue the
command rs.conf(). To check the status of
replica set issue the command rs.status().
Add Members to
Replica Set
To add members to replica set, start
mongod instances on multiple machines.
Now start a mongo client and issue a
command rs.add().
Syntax
The basic syntax of rs.add() command is
as follows −
>rs.add(HOST_NAME:PORT)
Example
Suppose your mongod instance name
is mongod1.net and it is running on
port 27017. To add this instance to replica
set, issue the command rs.add()in Mongo
client.
>rs.add("mongod1.net:27017")
>
Why Sharding?
∙ In replication, all writes go to master node
∙ Latency sensitive queries still go to master
∙ Single replica set has limitation of 12 nodes
∙ Memory can't be large enough when active
dataset is big
∙ Local disk is not big enough
∙ Vertical scaling is too expensive
Sharding in MongoDB
The following diagram shows the sharding
in MongoDB using sharded cluster.
Example
Start your mongod server. Assuming that
your mongod server is running on the
localhost and port 27017, open a command
prompt and go to the bin directory of your
mongodb instance and type the
command mongodump
Consider the mycol collection has the
following data.
>mongodump
The command will connect to the server
running at 127.0.0.1 and port 27017 and
back all data of the server to
directory /bin/dump/. Following is the
output of the command −
Restore data
To restore backup data
MongoDB's mongorestore command is
used. This command restores all of the
data from the backup directory.
Syntax
The basic syntax
of mongorestore command is −
>mongorestore
Following is the output of the command −
When you are preparing a MongoDB
deployment, you should try to understand
how your application is going to hold up in
production. It’s a good idea to develop a
consistent, repeatable approach to
managing your deployment environment so
that you can minimize any surprises once
you’re in production.
The best approach incorporates
prototyping your set up, conducting load
testing, monitoring key metrics, and using
that information to scale your set up. The
key part of the approach is to proactively
monitor your entire system - this will help
you understand how your production
system will hold up before deploying, and
determine where you will need to add
capacity. Having insight into potential
spikes in your memory usage, for example,
could help put out a write-lock fire before it
starts.
To monitor your deployment, MongoDB
provides some of the following commands
−
mongostat
This command checks the status of all
running mongod instances and return
counters of database operations. These
counters include inserts, queries, updates,
deletes, and cursors. Command also
shows when you’re hitting page faults, and
showcase your lock percentage. This
means that you're running low on memory,
hitting write capacity or have some
performance issue.
To run the command, start your mongod
instance. In another command prompt, go
to bin directory of your mongodb
installation and type mongostat.
D:\set up\mongodb\bin>mongostat
Following is the output of the command −
mongotop
This command tracks and reports the read
and write activity of MongoDB instance on
a collection basis. By
default, mongotop returns information in
each second, which you can change it
accordingly. You should check that this
read and write activity matches your
application intention, and you’re not firing
too many writes to the database at a time,
reading too frequently from a disk, or are
exceeding your working set size.
To run the command, start your mongod
instance. In another command prompt, go
to bin directory of your mongodb
installation and type mongotop.
D:\set up\mongodb\bin>mongotop
Following is the output of the command −
To change mongotop command to return
information less frequently, specify a
specific number after the mongotop
command.
D:\set up\mongodb\bin>mongotop 30
The above example will return values every
30 seconds.
Apart from the MongoDB tools, 10gen
provides a free, hosted monitoring service,
MongoDB Management Service (MMS),
that provides a dashboard and gives you a
view of the metrics from your entire
cluster.
In this chapter, we will learn how to set up
MongoDB JDBC driver.
Installation
Before you start using MongoDB in your
Java programs, you need to make sure that
you have MongoDB JDBC driver and Java
set up on the machine. You can check Java
tutorial for Java installation on your
machine. Now, let us check how to set up
MongoDB JDBC driver.
∙ You need to download the jar from the
path Download mongo.jar. Make sure to
download the latest release of it.
∙ You need to include the mongo.jar into your
classpath.
Connect to Database
To connect database, you need to specify
the database name, if the database doesn't
exist then MongoDB creates it
automatically.
Following is the code snippet to connect to
the database −
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
// Creating Credentials
MongoCredential credential;
credential =
MongoCredential.createCredential("sampleUser",
"myDb",
"password".toCharArray());
System.out.println("Connected to the database
successfully");
MongoDatabase database =
mongo.getDatabase("myDb");
Create a Collection
To create a
collection, createCollection() method
of com.mongodb.client.MongoDatabase cl
ass is used.
Following is the code snippet to create a
collection −
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
// Creating Credentials
MongoCredential credential;
credential =
MongoCredential.createCredential("sampleUser",
"myDb",
"password".toCharArray());
MongoDatabase database =
mongo.getDatabase("myDb");
//Creating a collection
database.createCollection("sampleCollection");
System.out.println("Collection created
successfully");
Getting/Selecting a
Collection
To get/select a collection from the
database, getCollection() method
of com.mongodb.client.MongoDatabase cl
ass is used.
Following is the program to get/select a
collection −
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
MongoCredential credential;
credential =
MongoCredential.createCredential("sampleUser",
"myDb",
"password".toCharArray());
MongoDatabase database =
mongo.getDatabase("myDb");
// Creating a collection
System.out.println("Collection created
successfully");
// Retieving a collection
MongoCollection<Document> collection =
database.getCollection("myCollection");
System.out.println("Collection myCollection
selected successfully");
Insert a Document
To insert a document into
MongoDB, insert() method
of com.mongodb.client.MongoCollection cl
ass is used.
Following is the code snippet to insert a
document −
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
// Creating Credentials
MongoCredential credential;
credential =
MongoCredential.createCredential("sampleUser",
"myDb",
"password".toCharArray());
MongoDatabase database =
mongo.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection =
database.getCollection("sampleCollection");
System.out.println("Collection sampleCollection
selected successfully");
Document document = new Document("title",
"MongoDB")
.append("id", 1)
.append("description", "database")
.append("likes", 100)
.append("url",
"http://www.tutorialspoint.com/mongodb/")
collection.insertOne(document);
System.out.println("Document inserted
successfully");
Retrieve All
Documents
To select all documents from the
collection, find() method
of com.mongodb.client.MongoCollection cl
ass is used. This method returns a cursor,
so you need to iterate this cursor.
Following is the program to select all
documents −
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
// Creating Credentials
MongoCredential credential;
credential =
MongoCredential.createCredential("sampleUser",
"myDb",
"password".toCharArray());
System.out.println("Connected to the database
successfully");
MongoDatabase database =
mongo.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection =
database.getCollection("sampleCollection");
System.out.println("Collection sampleCollection
selected successfully");
FindIterable<Document> iterDoc =
collection.find();
int i = 1;
// Getting the iterator
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
i++;
Update Document
To update a document from the
collection, updateOne() method
of com.mongodb.client.MongoCollection cl
ass is used.
Following is the program to select the first
document −
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
MongoCredential credential;
credential =
MongoCredential.createCredential("sampleUser",
"myDb",
"password".toCharArray());
MongoDatabase database =
mongo.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection =
database.getCollection("sampleCollection");
System.out.println("Collection myCollection
selected successfully");
collection.updateOne(Filters.eq("id", 1),
Updates.set("likes", 150));
System.out.println("Document update
successfully...");
FindIterable<Document> iterDoc =
collection.find();
int i = 1;
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
i++;
Delete a Document
To delete a document from the collection,
you need to use the deleteOne()method of
the com.mongodb.client.MongoCollection
class.
Following is the program to delete a
document −
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
// Creating Credentials
MongoCredential credential;
credential =
MongoCredential.createCredential("sampleUser",
"myDb",
"password".toCharArray());
MongoDatabase database =
mongo.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection =
database.getCollection("sampleCollection");
System.out.println("Collection sampleCollection
selected successfully");
collection.deleteOne(Filters.eq("id", 1));
System.out.println("Document deleted
successfully...");
FindIterable<Document> iterDoc =
collection.find();
int i = 1;
// Getting the iterator
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
i++;
Dropping a Collection
To drop a collection from a database, you
need to use the drop() method of
the com.mongodb.client.MongoCollection
class.
Following is the program to delete a
collection −
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
// Creating Credentials
MongoCredential credential;
credential =
MongoCredential.createCredential("sampleUser",
"myDb",
"password".toCharArray());
MongoDatabase database =
mongo.getDatabase("myDb");
// Creating a collection
System.out.println("Collections created
successfully");
// Retieving a collection
MongoCollection<Document> collection =
database.getCollection("sampleCollection");
// Dropping a Collection
collection.drop();
System.out.println("Collection dropped
successfully");
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
// Creating Credentials
MongoCredential credential;
credential =
MongoCredential.createCredential("sampleUser",
"myDb",
"password".toCharArray());
MongoDatabase database =
mongo.getDatabase("myDb");
System.out.println("Collection created
successfully");
System.out.println(name);
Make a Connection
and Select a Database
To make a connection, you need to specify
the database name, if the database doesn't
exist then MongoDB creates it
automatically.
Following is the code snippet to connect to
the database −
<?php
// connect to mongodb
$m = new MongoClient();
// select a database
$db = $m->mydb;
?>
Create a Collection
Following is the code snippet to create a
collection −
<?php
// connect to mongodb
$m = new MongoClient();
// select a database
$db = $m->mydb;
$collection = $db->createCollection("mycol");
echo "Collection created succsessfully";
?>
Insert a Document
To insert a document into
MongoDB, insert() method is used.
Following is the code snippet to insert a
document −
<?php
// connect to mongodb
$m = new MongoClient();
$db = $m->mydb;
$collection = $db->mycol;
$document = array(
"url" =>
"http://www.tutorialspoint.com/mongodb/",
);
$collection->insert($document);
?>
// connect to mongodb
$m = new MongoClient();
// select a database
$db = $m->mydb;
$collection = $db->mycol;
$cursor = $collection->find();
}
?>
Update a Document
To update a document, you need to use the
update() method.
In the following example, we will update the
title of inserted document to MongoDB
Tutorial. Following is the code snippet to
update a document −
<?php
// connect to mongodb
$m = new MongoClient();
echo "Connection to database successfully";
// select a database
$db = $m->mydb;
$collection = $db->mycol;
$collection->update(array("title"=>"MongoDB"),
array('$set'=>array("title"=>"MongoDB Tutorial")));
$cursor = $collection->find();
// iterate cursor to display title of documents
?>
Delete a Document
To delete a document, you need to use
remove() method.
In the following example, we will remove
the documents that has the title MongoDB
Tutorial. Following is the code snippet to
delete a document −
<?php
// connect to mongodb
$m = new MongoClient();
// select a database
$db = $m->mydb;
$collection = $db->mycol;
$collection->remove(array("title"=>"MongoDB
Tutorial"),false);
$cursor = $collection->find();
?>
When the program is executed, it will
produce the following result −
Connection to database successfully
Database mydb selected
Collection selected succsessfully
Documents deleted successfully
In the above example, the second
parameter is boolean type and used
for justOne field of remove() method.
Remaining MongoDB methods findOne(),
save(), limit(), skip(), sort()etc. works same
as explained above.
Comparison Query operators
Nam Description
e
Projection operator
Name Description