MongoDB
MongoDB
Create Database
use
Command
MongoDB
use DATABASE_NAME is used to create database. The command will create
a new database, if it doesn't exist otherwise it will return the
existing database.
Syntax:
use
DATABASE_NAME
Example:
>use
mydb=========here mydb is database name
To
check current database
>db
This
will show current working db
To
show all databases
>show
dbs
MongoDB
Drop Database
dropDatabase()
Method
MongoDB
db.dropDatabase() command is used to drop a existing database.
Basic
syntax of dropDatabase() command is as follows:
db.dropDatabase()
MongoDB
Create Collection
createCollection()
Method
MongoDB
db.createCollection(name, options) is used to create collection.
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 used to specify configuration of collection
Parameter Type Description
Name String Name
of the collection to be created
Options Document (Optional)
Specify options about memory size and indexing
Options
parameter is optional, so you need to specify only name of the
collection. Following is the list of options you can use:
EXAMPLES:
Basic
syntax of createCollection() method without options is as follows
>use
test
switched
to db test
>db.createCollection("mycollection")
{
"ok" : 1 }
>
You
can check the created collection by using the command show
collections
>show
collections========this will show list collections in ur db
Following
example shows the syntax of createCollection() method with few
important options:
>db.createCollection("mycol",
{ capped : true, autoIndexID : true, size : 6142800, max : 10000 } )
{
"ok" : 1 }
>
In mongodb you don't need to create collection. MongoDB creates
collection automatically, when you insert some document.
>db.tutorialspoint.insert({"name"
: "tutorialspoint"})
>show
collections
mycol
mycollection
system.indexes
tutorialspoint
MongoDB
Drop Collection
drop()
Method
MongoDB's
db.collection.drop() is used to drop a collection from the database.
db.COLLECTION_NAME.drop()
EXAMPLE:
First,
check the available collections into your database mydb
>use
mydb
switched
to db mydb
>show
collections
mycol
mycollection
system.indexes
tutorialspoint
>
Now
drop the collection with the name mycollection
>db.mycollection.drop()
true
>
MongoDB
Datatypes
MongoDB
supports many datatypes whose list is given below:
String
:
This is most commonly used datatype to store the data. String in
mongodb must be UTF-8 valid.
Integer
:
This type is used to store a numerical value. Integer can be 32 bit
or 64 bit depending upon your server.
Boolean
:
This type is used to store a boolean (true/ false) value.
Double
:
This type is used to store floating point values.
Min/
Max keys :
This type is used to compare a value against the lowest and highest
BSON elements.
Arrays
:
This type is used to store arrays or list or multiple values into one
key.
Timestamp
:
ctimestamp. This can be handy for recording when a document has been
modified or added.
Object
:
This datatype is used for embedded documents.
Null
:
This type is used to store a Null value.
Symbol
:
This datatype is used identically to a string however, it's generally
reserved for languages that use a specific symbol type.
Date
:
This datatype is used to store the current date or time in UNIX time
format. You can specify your own date time by creating object of Date
and passing day, month, year into it.
Object
ID :
This datatype is used to store the document’s ID.
Binary
data :
This datatype is used to store binay data.
Code
:
This datatype is used to store javascript code into document.
Regular
expression :
This datatype is used to store regular expression
MongoDB
- Query Document
find()
Method
To
query data from MongoDB collection, you need to use MongoDB's find()
method.
>db.COLLECTION_NAME.find()
find()
method will display all the documents in a non structured way.
pretty()
Method
To
display the results in a formatted way, you can use pretty() method.
>db.mycol.find().pretty()
findOne() method
Apart
from find() method there is findOne() method,
that reruns only one document.
RDBMS
Where Clause Equivalents in MongoDB
To
query the document on the basis of some condition, you can use
following operations
Operation
|
Syntax
|
Example
|
RDBMS
Equivalent
|
Equality
|
{<key>:<value>}
|
db.mycol.find({"by":"tutorials
point"}).pretty()
|
where
by = 'tutorials point'
|
Less
Than
|
{<key>:{$lt:<value>}}
|
db.mycol.find({"likes":{$lt:50}}).pretty()
|
where
likes < 50
|
Less
Than Equals
|
{<key>:{$lte:<value>}}
|
db.mycol.find({"likes":{$lte:50}}).pretty()
|
where
likes <= 50
|
Greater
Than
|
{<key>:{$gt:<value>}}
|
db.mycol.find({"likes":{$gt:50}}).pretty()
|
where
likes > 50
|
Greater
Than Equals
|
{<key>:{$gte:<value>}}
|
db.mycol.find({"likes":{$gte:50}}).pretty()
|
where
likes >= 50
|
Not
Equals
|
{<key>:{$ne:<value>}}
|
db.mycol.find({"likes":{$ne:50}}).pretty()
|
where
likes != 50
|
AND
in MongoDB
In
the find() method if you pass multiple keys by separating them by ','
then MongoDB treats it AND condition.
>db.mycol.find({key1:value1,
key2:value2}).pretty()
Below
given example will show all the tutorials written by 'tutorials
point' and whose title is 'MongoDB Overview'
>db.mycol.find({"by":"tutorials
point","title": "MongoDB Overview"}).pretty()
{
"_id":
ObjectId(7df78ad8902c),
"title":
"MongoDB Overview",
"description":
"MongoDB is no sql database",
"by":
"tutorials point",
"url":
"http://www.tutorialspoint.com",
"tags":
["mongodb", "database", "NoSQL"],
"likes":
"100"
}
>
For
the above given example equivalent where clause will be ' where
by='tutorials point' AND title='MongoDB Overview' '. You can pass any
number of key, value pairs in find clause.
OR
in MongoDB
To
query documents based on the OR condition, you need to use $or
keyword. Basic syntax of OR is shown below:
>db.mycol.find(
{
$or:
[
{key1: value1}, {key2:value2}
]
}
).pretty()
Below
given 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),
"title":
"MongoDB Overview",
"description":
"MongoDB is no sql database",
"by":
"tutorials point",
"url":
"http://www.tutorialspoint.com",
"tags":
["mongodb", "database", "NoSQL"],
"likes":
"100"
}
>
Using
AND and OR together
Below
given example will show the documents that have likes greater than
100 and whose title is either 'MongoDB Overview' or by is 'tutorials
point'. Equivalent sql where clause is 'where likes>10 AND (by =
'tutorials point' OR title = 'MongoDB Overview')'
>db.mycol.find("likes":
{$gt:10}, $or: [{"by": "tutorials point"},
{"title": "MongoDB Overview"}] }).pretty()
{
"_id":
ObjectId(7df78ad8902c),
"title":
"MongoDB Overview",
"description":
"MongoDB is no sql database",
"by":
"tutorials point",
"url":
"http://www.tutorialspoint.com",
"tags":
["mongodb", "database", "NoSQL"],
"likes":
"100"
}
>
MongoDB
Update Document
MongoDB's
update() and save() methods are used to update document into a
collection. The update() method update 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 values in the existing document.
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA,
UPDATED_DATA)
Consider
the mycol collectioin has following data.
{
"_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB
Overview"}
{
"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL
Overview"}
{
"_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials
Point Overview"}
By
default mongodb will update only single document, to update multiple
you need to set a paramter 'multi' to true.
>db.mycol.update({'title':'MongoDB
Overview'},{$set:{'title':'New MongoDB Tutorial'}},{multi:true})
MongoDB
Save() Method
The
save() method replaces the existing document with the new document
passed in save() method
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
Following
example will replace the document with the _id
'5983548781331adf45ec7'
>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"}
MongoDB Delete
Document
remove()
Method
MongoDB's
remove() method is used to remove 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.
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Consider
the student collectioin has following data.
db.student.find().pretty()
{
"_id"
: ObjectId("54fbd3d82ca95514f09447fb"),
"sid"
: "001",
"sname"
: "satyanarayana",
"marks"
: "33"
}
{
"_id"
: ObjectId("54fbd40a2ca95514f09447fc"),
"sid"
: "002",
"sname"
: "sai",
"ramu"
: "55"
}
{
"_id"
: ObjectId("54fbd43e2ca95514f09447fd"),
"sid"
: "003",
"sname"
: "sai",
"marks"
: "66"
>db.student.remove({‘sname’:’sai’})=====this
will remove all records whose name is satya
If
we want to remov only one record use the following
Remove
only one
If
there are multiple records and you want to delete only first record,
then set justOne parameter in remove() method
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
>db.student.remove({‘sname’:’sai’},1)====this
will remove only one document
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({})=======this
will remove the all documents from collection
>db.mycol.find()
MongoDB
Projection
In
mongodb projection meaning is selecting only necessary data rather
than selecting whole of the data of a document. If a document has 5
fields and you need to show only 3, then select only 3 fields from
them.
The
find() Method
MongoDB's
find() method, explained in MongoDB Query Document accepts second
optional parameter that is list of fields that you want to retrieve.
In MongoDB when you execute find() method, then it displays all
fields of a document. To limit this you need to set list of fields
with value 1 or 0. 1 is used to show the filed while 0 is used to
hide the field.
>db.COLLECTION_NAME.find({},{KEY:1})
Following
example will display the title of the document while quering the
document.
>db.mycol.find({},{"title":1,_id:0})
{"title":"MongoDB
Overview"}
{"title":"NoSQL
Overview"}
{"title":"Tutorials
Point 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
MongoDB
Limit Records
The
Limit() Method
To
limit the records in MongoDB, you need to use limit() method. limit()
method accepts one number type argument, which is number of documents
that you want to displayed.
Syntax:
>db.COLLECTION_NAME.find().limit(NUMBER)
Following
example will display only 2 documents while quering the document.
>db.mycol.find({},{"title":1,_id:0}).limit(2)
{"title":"MongoDB
Overview"}
{"title":"NoSQL
Overview"}
>
If you don't
specify number argument in limit() method then it will display all
documents from the collection.
MongoDB
Skip() Method
Apart
from limit() method there is one more method skip() which also
accepts number type argument and used to skip number of documents.
>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
Following
example will only display only second document.
>db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL
Overview"}
>
Please
note default value in skip() method is 0
MongoDB
Sort Documents
sort()
Method
To
sort documents in MongoDB, you need to use sort() method. sort()
method accepts a document containing list offields along with their
sorting order. To specify sorting order 1 and -1 are used. 1 is used
for ascending order while -1 is used for descending order.
Basic
syntax of sort() method is as follows
>db.COLLECTION_NAME.find().sort({KEY:1})
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
Please
note if you don't specify the sorting preference, then sort() method
will display documents in ascending order.
MongoDB
Indexing
Indexes
support the efficient resolution of queries. Without indexes, MongoDB
must scan every document of a collection to select those documents
that match the query statement. This scan is highly inefficient and
require the mongod to process a large volume of data.
Indexes
are special data structures, that store a small portion of the data
set in an easy to traverse form. The index stores the value of a
specific field or set of fields, ordered by the value of the field as
specified in index.
ensureIndex()
Method
To
create an index you need to use ensureIndex() method of mongodb.
Basic
syntax of ensureIndex() method is as follows()
>db.COLLECTION_NAME.ensureIndex({KEY:1})
Here
key is the name of filed on which you want to create index and 1 is
for ascending order. To create index in descending order you need to
use -1.
>db.mycol.ensureIndex({"title":1})
In
ensureIndex() method you can pass multiple fields, to create index on
multiple fields.
>db.mycol.ensureIndex({"title":1,"description":-1})
>
ensureIndex()
method also accepts list of options (which are optional), whose list
is given below:
MongoDB
Aggregation
Aggregations
operations process data records and return computed results.
Aggregation operations group values from multiple documents together,
and can perform a variety of operations on the grouped data to return
a single result. In sql count(*) and with group by is an equivalent
of mongodb aggregation.
aggregate()
Method
For
the aggregation in mongodb you should use aggregate() method.
Basic
syntax of aggregate() method is as follows
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
In
the collection you have the following data
MongoDB
Create Backup
Dump
MongoDB Data
To
create backup of database in mongodb you should use mongodump
command. This command will dump all data of your server into dump
directory. There are many options available by which you can limit
the amount of data or create backup of your remote server.
Basic
syntax of mongodump command is as follows
>mongodump