MONGODB
Document Database
DOCUMENT ORIENTED
DATABASE
store data in the form of documents
document can be in a JSON, BSON, XML, YAML, etc format
Documents are retrieved from the database using unique key that
represents that document.
key may be a simple string, URI, or a path
Support data sharding
MONGODB
open-source document database
written in c++
cross-platform
Provides
high performance
high availability
easy scalability
works on concept of collection and document.
DATABASE
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
group of MongoDB documents
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
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
RDBMS VS MONGODB
RDBMS
MongoDB
Database
Database
Table
Collection
Tuple/Row
Document
Column
Field
Table Join
Embedded Documents
Primary Key
Primary Key (Default key
_id provided by mongodb
itself)
SAMPLE DOCUMENT
12 bytes hexadecimal
number
Assures the uniqueness of
every document
ID
1
Current timestamp
Machine ID
MongoDB
server
process
ID
10
11
12
Simple
Incremental
value
WHY USE MONGODB?
Document Oriented Storage : Data is stored in the form of JSON
style documents
Index on any attribute
Replication & High Availability
Auto-Sharding
Rich Queries
Fast In-Place Updates
Professional Support By MongoDB
MONGODB ENVIRONMENT
Download from
https://www.mongodb.com/
Create data directory to store all data. MongoDBs default data
directory path is \data\db.
Specify an alternate path for data files using the --dbpath option to
mongod.exe
mongod.exe -dbpath "e:\mongodb\data\db
MongoDB starts
2016-06-30T11:53:43.521+0530 I NETWORK [initandlisten] waiting for
connections on port 27017
2016-06-30T11:57:16.861+0530 I NETWORK [initandlisten] connection accepted
from 127.0.0.1:51595 #1 (1 connection now open)
Open another command prompt
c:\Program Files\MongoDB\Server\3.2\bin>mongo
Welcome to the MongoDB shell.
COMMANDS
Command
Description
Example
show dbs
Display list of database (with at least
one document)
show dbs
use db_name
Create new database db_name
Change database
use mydb
db
Display current database
db
db.dropDatabase()
Delete database
{ "dropped" : "mydb", "ok" :
1}
db.createCollection(n Create collection
ame, options)
name: String: Name of collection
options: Document : optional
db.createCollection("mycolle
ction")
show collections
Display collections in current database
show collections
db.coll_name.insert(
{key:value})
Insert documents in collection coll_name db.movie.insert({"name":"lo
velyn"})
db.coll_name.drop()
Delete collection from database
db.movie.drop()
CREATE COLLECTIONS
(OPTIONS)
Field
Type
Description
capped
Boolean
(Optional) If true, enables a capped collection. Capped collection
is a collection fixed size collecction that automatically
overwrites its oldest entries when it reaches its maximum size.
If you specify true, you need to specify size parameter
also.
autoIndex
ID
Boolean
(Optional) If true, automatically create index on _id field.s
Default value is false.
size
number
(Optional) Specifies a maximum size in bytes for a capped
collection. If If capped is true, then you need to specify
this field also.
max
number
(Optional) Specifies the maximum number of documents
allowed in the capped collection.
CAPPED COLLECTIONS
to store data in the same order it is inserted
fixed size
high-performance
"auto-FIFO age-Out
can't remove an individual object from the capped collection
maximum size for a capped collection is 1e9(i.e. 1X109) for 32 bit
machines. For 64 bit machines, there is no theoretical limit.
Practically, it can be extended till your system resources permit.
can be used for logging, caching and auto archiving
Command
Description
Example
db.COLLECTION_NAM Insert documents in
E.insert(document)
collection
>
db.tweet.insert({id:1,location:"coimbatore",tw
eet:"kjdhdskjh"})
WriteResult({ "nInserted" : 1 })
>
db.tweet.insert({id:2,location:"coimbatore",tw
eet:"kjdhdskjh"},{id:3})
db.COLLECTION_NAM find()
E.find()
display all the
documents in a non
structured way.
db.tweet.find().pretty()
{
"_id" :
ObjectId("577a22bfe94a2882699e6b7a"),
"id" : 1,
"location" : "coimbatore",
"tweet" : "kjdhdskjh"
}
{
"_id" :
ObjectId("577a22dee94a2882699e6b7b"),
"id" : 2,
"location" : "coimbatore",
"tweet" : "kjdhdskjh"
}
pretty()
display the results in a
formatted way
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
OR IN MONGODB
Syntax
Example
>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB
Overview"}]}).pretty()
>db.mycol.find(
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
$or: [
"description": "MongoDB is no sql database",
{key1: value1}, {key2:value2}
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
).pretty()
"likes": "100"
}
SHOW THE DOCUMENTS THAT HAVE LIKES
GREATER THAN 100 AND WHOSE TITLE IS EITHER
'MONGODB OVERVIEW' OR BY IS 'TUTORIALS POINT'
>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"
}
UPDATE() METHOD
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA,
UPDATED_DATA)
>db.mycol.update({'title':'MongoDB Overview'},
{$set:{'title':'New MongoDB Tutorial'}},{multi:true})
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
>db.mycol.save(
{
"_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials
Point Overview",
"by":"Tutorials Point"
}
)
REMOVE() METHOD
>db.COLLECTION_NAME.remove(DELETION_CRITERIA)
>db.mycol.remove({'title':'MongoDB Overview'})
Delete only first record
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
Remove All documents
>db.mycol.remove()
MONGODB
DATATYPES
MongoDB stores documents on disk in the BSON serialization
format.
BSON is a binary representation of JSON documents, though BSON
data format provides more data types than JSON
Type
Description
Number
Double
Represents a float value.
String
BSON strings are UTF-8
Object
Represents an embedded documents.
Array
Sets or lists of values can be represented as arrays:
Binary data
Binary data is a string of arbitrary bytes, it cannot be manipulated from
the shell.
Object id
ObjectIds (MongoDB document identifier, equivalent to a Primary key)
are: small, likely unique, fast to generate, and ordered. These values
consists of 12-bytes, where the first four bytes are a timestamp that
reflect the ObjectIds creation.
Boolean
A logical true or false. Use to evaluate whether a condition is true or false
Date
BSON Date is a 64-bit integer that represents the number of milliseconds
since the Unix epoch (Jan 1, 1970). This results in a representable date
range of about 290 million years into the past and future.
Null
It represents both a null value and a nonexistent field.
10
Regular
Expression
RegExp maps directly to a Javascript RegExp
11
JavaScript
13
Symbol
Not supported by the shell. If the shell gets a symbol from the database, it
14
Type
Description
JavaScript
(with
scope)
Number
15
32-bit
integer
Numbers without decimal points will be saved as 32-bit
16
integers.
Timestam
p
BSON has a special timestamp type for internal
MongoDB use and is not associated with the regular
Date type. Timestamp values are a 64 bit value
where :
17
-- the first 32 bits are a time_t value (seconds since the
Unix epoch).
-- the second 32 bits are an incrementing ordinal for
operations within a given second.
64-bit
integer
Numbers without a decimal point will be saved and
returned as 64-bit integers.
18
Min key
MinKey compare less than all other possible BSON
element values, respectively, and exist primarily for
internal use.
255
Max key
MaxKey compare greater than all other possible BSON
element values, respectively, and exist primarily for
internal use.
127
http://www.w3resource.com/mongodb/mongodb-data-types.php
http://www.tutorialspoint.com/mongodb/mongodb_datatype.htm