Sunteți pe pagina 1din 47

QUICK

R E F E R E NCE CAR DS
FOR MONGOD B 3.4

U p d a t e d J u ly 2 017
W H AT I S M O N G O D B ?

MONGODB I S AN OP E N-SOU RCE,


G E N E R A L P U R P O S E D ATA B A S E .

Instead of storing data in rows and columns as a relational database does,


MongoDB uses a document data model, and stores a binar y form of JSON
documents called BSON. Documents contain one or more fields, and each
field contains a value of a specific data type, including arrays and binar y
data. Documents are stored in collections, and collections are stored in
databases. It may be helpful to think of documents as roughly equivalent
to rows in a relational database; fields as equivalent to columns; and
collections as tables. There are no fixed schemas in MongoDB, so
documents can var y in structure and can be adapted dynamically.

MongoDB provides full index suppor t, including secondar y, compound and


geospatial indexes. MongoDB also features a rich quer y language with
power ful analy tics capabilities, atomic update modifiers, tex t search, and
MapReduce for complex in-place data analysis.

Built-in replication with automated failover provides high availability. Auto-


sharding enables horizontal scaling for large deployments. MongoDB also
provides native, idiomatic drivers for all popular programming languages
and frameworks to make development natural.

MongoDB is fully secure, with authentication, authorization & role-based


access control, integration with auth mechanisms like LDAP and Kerberos,
end-to-end encr yption, auditing, and field-level redaction.
C OM MAN D H E LP E R S
C OM MAN D H E LP E R S

The following table lists some common help commands which are available in the
mongo shell:

help Show help.

db.help() Show help for database methods.

Show help on collection methods.


T h e < c olle c tio n > c a n b e t h e
db.<collection>.help()
name of an existing collection or a
non-existing collection.

Print a list of all databases on the


show dbs
s e r v e r.

S w i t c h c u r r e n t d a t a b a s e t o < d b >.
use <db> The mongo shell variable db is set
to the current database.

Print a list of all collections for


show collections
the current database.

Print a list of users for the current


show users
database.

Print a list of all roles, both


show roles u s e r- d e f i n e d a n d b u i l t- i n , f o r t h e
current database.

Print the five most recent


show profile operations that took 1 millisecond
or more.

Print a list of all available


show databases
databases.

F O R M O R E I N F O R M AT I O N

https://docs.mongodb.com/manual/reference/mongo-shell/
CR U D M ETHODS
CR U D M ETHODS

Queries t ypically take the following form:

db.<collection>.<method>( <filter>, <options>)

db refers to the current database. <collection> is the name of the target


collection for your quer y. For <method>, substitute the desired quer y method,
(examples below). Each method has its own <options> for what it will do with the
matching document(s).

Inser ts a document into a


db.collection.insertOne()
collection.

Inser ts multiple documents into a


db.collection.insertMany()
collection.

Selects documents in a collection


db.collection.find() based on the filter and returns a
cursor to the selected documents.

Updates a single document within


db.collection.updateOne()
t h e c o l l e c t i o n b a s e d o n t h e f i l t e r.

Updates all documents within the


db.collection.updateMany()
c o l l e c t i o n t h a t m a t c h t h e f i l t e r.

Replaces a single document within


db.collection.replaceOne()
t h e c o l l e c t i o n b a s e d o n t h e f i l t e r.

Removes a single document from a


db.collection.deleteOne()
c o l l e c t i o n b a s e d o n t h e f i l t e r.

Removes all documents that match


db.collection.deleteMany()
the filter from a collection.

F O R M O R E I N F O R M AT I O N

https://docs.mongodb.com/manual/crud/
Q U E R Y F I LT E R PA R A M E T E R S
A N D W H AT T H E Y M ATC H
Q U E R Y F I LT E R PA R A M E T E R S
A N D W H AT T H E Y M ATC H

MongoDB uses a key-value structure to create quer y filter parameters, which you
can use in the mongo shell or with a driver in a client application. For example, the
following quer y finds all documents in the collection named inventory in which the
qty field contains a value greater than 10:

db.inventory.find({ "qty" : { $gt: 10 }})

Queries take documents as quer y filter parameters, shown as examples below.


Multiple filter parameters can be included in one document , separated by commas.

D o c s w h e r e a i s 10 o r a n a r r a y
{a: 10}
c o n t a i n i n g t h e v a l u e 10 .

D o c s w h e r e a i s 10 a n d b i s
{a: 10, b: "hello"}
" h ello".

D o c s w h e r e a i s g r e a t e r t h a n 10 .
Also available:
{a: {$gt: 10}}
$lt (<) , $g te (>=) , $lte (<=) ,
a n d $n e ( ! =) .

D o c s w h e r e a i s e i t h e r 10 o r
{a: {$in: [10, "hello"]}}
" h ello".

Docs where a is an array


{a: {$all: [10, "hello"]}} c o n t a i n i n g b o t h 10 a n d
" h ello".
Docs where a is an embedded
{"a.b": 10}
d o c u m e n t w i t h b e q u a l t o 10 .

Docs where a is an array that


{a: {$elemMatch: {b: 1, c: contains an element with both b
2}}} equal to 1 and c equal to 2.

{$or: [{a: 1}, {b: 2}]} Docs where a is 1 or b is 2.

Docs where a begins with the


let ter m. One can also use the
{a: /^m/}
r e g e x o p e r a t o r : {a: {$r e g e x:
"^ m"}}

{a: {$mod: [10, 1]}} D o c s w h e r e a m o d 10 i s 1 .

{a: {$type: "string"}} Docs where a is a string.

D o c s t h a t c o n t a i n " h ello" o n a
{$text: {$search: "hello"}}
full tex t search.

F O R M O R E I N F O R M AT I O N

https://docs.mongodb.com/manual/reference/bson-types
https://docs.mongodb.com/manual/reference/operator/query/text/

QUERIES
{ a:
{ $near:
{ $geometry:
Docs sor ted in order of a nearest
{
to far thest from the given
type: "Point",
coordinates. There must be a
coordinates:
2dsphere index on a for this t ype
[ -73.9876, 40.7574
o f q u e r y. C o o r d i n a t e s i n G e o J S O N
]
are listed in the order longitude,
}
latitude.
}
}
}

{ a:
{ $geoWithin:
{ $geometry:
{
type : "Polygon",
coordinates:
Doc s where a exists entirely
[ [ [ 0, 0 ],
within the specified GeoJSON
[ 3, 6 ], Polygon.
[ 6, 1 ],
[ 0, 0 ] ] ]
}
}
}
}

QUERIES
{ a:
{ $geoIntersects:
{ $geometry:
{
type: "Polygon",
Coordinates:
Docs where a intersects with
[ [ [ 0, 0 ],
the specified GeoJSON Polygon,
[ 3, 6 ],
including cases where a and the
[ 6, 1 ],
polygon share an edge.
[ 0, 0 ] ] ]
}
}
}
}

{ a:
{ $nearSphere:
{ $geometry:
{
type : "Point",
D o c s w h e r e a i s a t l e a s t 10 0 0
Coordinates:
meters and at most 5000
[ -73.9876, 40.7574
meters from the specified
]
point , ordered from nearest to
},
far thest . $nearsphere requires a
$minDistance: 1000,
geospatial index .
$maxDistance: 5000
}
}
}

QUERIES
N OT I N D E X A B L E Q U E R I E S

Queries that cannot use indexes will be executed as collection scans scanning all
documents in the collection which will per form poorly at scale. The following are
examples of quer y t ypes which require a collection scan. To avoid collection scans,
these quer y forms should normally be accompanied by at least one other quer y term
which does use an index.

D o c s w h e r e a i s a n y t h i n g b u t 10
{a: {$nin: [10, "hello"]}}
o r " h ello".

Docs where a is an array with


{a: {$size: 3}}
exactly 3 elements.

{a: {$exists: true}} Docs containing an a field.

Docs where a matches the regular


{a: /foo.*bar/}
e x p r e s s i o n fo o.*b a r.

Docs where a is not a string.


{a: {$not: {$type: 2}}} $n o t n e g a t e s a n y o f t h e o t h e r
quer y operators.

F O R M O R E I N F O R M AT I O N

http://docs.mongodb.org/manual/tutorial/query-documents/
http://docs.mongodb.org/manual/reference/operator/query/
F I E L D U P D AT E O P E R ATO R S
F I E L D U P D AT E O P E R ATO R S

{$inc: {a: 2}} Increment a by 2.

{$set: {a: 5}} Set a to the value 5.

{$unset: {a: 1}} D e l e t e t h e a k e y.

Set a to the greater value, either


{$max: {a: 10}} c u r r e n t o r 10 . I f a d o e s n o t e x i s t ,
s e t a t o 10 .

Set a to the lowest value, either


{$min: {a: -10}} c u r r e n t o r -10 . I f a d o e s n o t e x i s t ,
s e t a t o -10 .

Set a to the product of the current


{$mul: {a: 2}} value of a and 2. If a does not
exist set a to 0.

{$rename: {a: "b"}} Rename field a to b.

{$setOnInsert: {a: 1}}, Set field a to 1 in case of upser t


{upsert: true} operation.
Set field a with the current date.
$c u r r e nt D ate c a n b e s p e c i f i e d
{$currentDate: {a: {$type:
as date or timestamp. Note that as
"date"}}}
of 3.0, date and timestamp are not
e q u i v a l e n t f o r s o r t o r d e r.

Per form the bit wise and operation


over a field:
10 0 0
010 0
{$bit: {a: {and: 7}}}
-------
110 0
S u p p o r t s a n d | x or | or
bitwise operators.

A R R AY U P D A T E O P E R A T O R S

{$push: {a: 1}} Append the value 1 to the array a .

Append both 1 and 2 to the


{$push: {a: {$each: [1, 2]}}}
array a .

A p p e n d 10 , 20 , a n d 30 t o t h e
array a , then trim the resulting
array to contain only the last 5
{$push: {a: {$each: [10, 20, elements. $slice can only be used
30], $slice: -5}}} w i t h t h e $ e a c h m o d i f i e r. N e g a t i v e
v a l u e s t r i m t o t h e l a s t <n u m>
elements, while positive values
t r i m t o t h e f i r s t <n u m> e l e m e n t s .

F I E L D U P D AT E O P E R AT O R S
I n s e r t 50 , 60 , a n d 70 s t a r t i n g
{$push: {a: {$each: [50, 60, at position 0 of the array a .
70], $position: 0}}} $position can only be used with
t h e $ e a c h m o d i f i e r.

Append the value 1 to the array a


{$addToSet: {a: 1}}
(i f t h e v a l u e d o e s n' t a l r e a d y e x i s t ) .

{$addToSet: {a: {$each: [1, Append both 1 and 2 to the array


2]}}} a (i f t h e y d o n' t a l r e a d y e x i s t ) .

Remove the last element from the


{$pop: {a: 1}}
array a .

Remove the first element from the


{$pop: {a: -1}}
array a .

Remove all values greater than 5


{$pull: {a: ($gt: 5}}}
from the array a .

Remove multiple occurrences of 5


{$pullAll: {a: [5, 6]}}
or 6 from the array a .

F O R M O R E I N F O R M AT I O N

http://docs.mongodb.org/manual/reference/operator/update/

F I E L D U P D AT E O P E R AT O R S
A G G R E G AT I O N F R A M E W O R K
A G G R E G AT I O N F R A M E W O R K :

The aggregation pipeline, par t of the MongoDB quer y language, is a framework for
data aggregation modeled on the concept of data processing pipelines. Documents
enter a multi-stage pipeline that transforms the documents into aggregated results.
Pipeline stages appear in an array. Documents pass through the stages in sequence.
Structure an aggregation pipeline using the following synta x:

db.<collection>.aggregate( [ { <stage1> }, { <stage2> } ... ]


)

C O M M O N A G G R E G A T I O N F R A M E W O R K S TA G E S

Passes only
{$match: {a: 10}} documents where a Similar to find( )
i s 10 .

Reshapes each
{$project: { a: 1, document to include Similar to find( )
_id:0}} only field a, removing projection
others.

Reshapes each
document to include
{$project: {
o n l y _ id a n d t h e n e w { a :1} => { n e w _ a :1}
new_a: "$a" }}
field new_a with the
value of a .

Reshapes each
document to include
{$project: { a: { a :1, b :10 } => { a :
o n l y _ id and field a,
{$add:["$a", "$b"]}}} 11}
set to the sum of a
and b.
Reshapes each
{$project: { stats: document to contain
{ o n l y _ id a n d t h e n e w
value: "$a", f i e l d st ats w h i c h
{ a : 10 , b : 2 } => {
fraction: contains embedded
s t a t s : { v a l u e : 10 ,
{$divide: ["$a", f i e l d s v a lu e , s e t t o f r a c t i o n : 5} }
"$b"]} the value of a , and
} fr a c tio n , s e t t o t h e
} } value of a divided by
b.

{ a : " h e l l o" } ,
{$group: { Groups documents by { a : "g o o d b y e " } ,
_id: "$a", field a and computes { a : " h e l l o" } => { _
count:{$sum:1} t h e c o u nt o f e a c h i d : " h e l l o", c o u n t : 2 } ,
} } distinct a value. { _ i d : "g o o d b y e ",
c o u n t :1}

{$group: {_id: "$a", Group documents by { a :1, b : "J o h n" } , { a :1,


field a with new field b : " M a r y " } => { _ i d :1,
names: {$addToSet:
names consisting of a n a m e s : [ "J o h n",
"$b"} set of b values. "Mary"] }
}}

Deconstructs array
{ a : [2 , 3 , 4] } => { a : 2 } ,
{$unwind: "$a"} field a into individual
{a:3}, {a:4}
documents of each.

Limits the set of


d o c u m e n t s t o 10 ,
{$limit: 10}
p a s s i n g t h e f i r s t 10
documents.

Sor ts results by field


{$sort: {a:1}}
a ascending.

A G G R E G AT I O N F R A M E W O R K
S k i p s t h e f i r s t 10
{$skip: 10} documents and passes
the rest.
The sample size
R a n d o m l y s e l e c t s 25
{$sample: {size: 25}} value must be a
documents.
p o s i t i v e i n t e g e r.

Per forms an
equalit y match
{$lookup: { f r o m t h e sk u f i e l d
from: "inventory", i n t h e i nv e nt o r y
This is a left outer
localField: join.
"item", c o l l e c t i o n t o t h e it e m
foreignField: field in the documents The collection
"sku", passed into this stage, s p e c i f i e d i n fr o m
as: "inventory_ then adds an array cannot be sharded,
docs" and must be in the
}} i nv e nt o r y _ d o c s t o
same database.
each document with
matching documents
f r o m i nv e nt o r y.

For each document


passed into this
stage, looks up its
n e a r e st A ir p o r t
{ $graphLookup: v a l u e i n t h e a ir p o r ts
{ collection and
from: "airports", recursively matches
startWith: t h e c o n n e c ts f i e l d
"$nearestAirport", t o t h e a ir p o r t f i e l d
connectFromField: w i t h i n t h e a ir p o r ts The collection
"connects",
collection. The s p e c i f i e d i n fr o m
connectToField:
operation specifies cannot be sharded,
"airport",
a ma ximum recursion and must be in the
maxDepth: 2,
depth of 2. The array same database.
depthField: "num-
Connections", d e sti n atio n s
as: "destina- is added to each
tions" document with
} the results of the
} recursive match,
including the field
n u m C o n n e c tio n s
with the value of the
depth of each match.

A G G R E G AT I O N F R A M E W O R K
Categorizes incoming
documents into
groups, called
{ $bucket:
bucket s , as defined
{ i n b o u n d a rie s .
groupBy: Any input document
Documents will be
with a value
"$price", g r o u p e d b y p ric e
outside of specified
boundaries: [ 0, i n t o b u c k e t s 0 -200
boundaries of or
a n d 200 -400 , w i t h
200, 400 ], a dif ferent BSON
inclusive lower bound
default: and exclusive upper
t ype will cause
"Other", the operation to
bound. Documents
t h r o w a n e r r o r.
output: with a price outside
This is avoided
{ of those bounds will
by specif ying a
be grouped into the
"count": d efa u lt b u c k e t .
b u c k e t O t h e r. T h e
{$sum: 1}, output is a set of
"titles" : T h e c o u nt f i e l d i s
documents, each with
included by default
{$push: "$title"} _ id s e t a s t h e l o w e r
w h e n t h e o utp ut i s
} bound of the bucket ,
not specified.
a count field with the
}
sum of documents,
} a n d a n a r r a y title s
o f t h e title f i e l d o f
incoming documents.

{ $bucketAuto: Categorizes incoming


documents into
{ O p t i o n a l l y, p r o v i d e
bucket s , grouping
groupBy: b y p ric e i n t o
a granularity to
ensure that bucket
"$price", 5 bucket s with
boundaries adhere
buckets: 5 bucket boundaries
to a par ticular
} automatically
number series. See
determined to at tempt
} the documentation
to evenly distribute
for more details.
documents.

A G G R E G AT I O N F R A M E W O R K
Groups incoming
documents based on
The expression can
{$sortByCount: the value of tags,
not evaluate to an
$tags} then computes the
object.
count of documents in
each distinct group.

Counts the documents


input to this stage and
{$count: "a"} returns a document
with a field a with the
value of the count .

Returns statistics
T h e $i n d e x St ats
regarding the use of
{$indexStats: {} } st age t akes an
each index for the
empt y document
collection.

{ $geoNear:
{ near:
{
Outputs documents
type:
in order of nearest Must be the
"Point", fir st st a g e o f a
to far thest from the
coordinates: pipeline.
specified point , adding
[ -73.9876, 40.7574
t h e f i e l d d ist w i t h a
] See documentation
value of the distance for other options to
},
from the specified p a s s t o $g e o N e a r.
distanceField:
point .
"dist"
}
}

Writes resulting
documents of
Must be the last
{$out: "myResults"} the pipeline into
stage of the pipeline
the collection
" m yR e su lts".

A G G R E G AT I O N F R A M E W O R K
FA C E T S

New in version 3.4, the $facet stage processes multiple aggregation pipelines
within a single stage on the same set of input documents. Each sub-pipeline has
its own field in the output document where its results are stored as an array of
documents. The $facet stage has the following form:

db.collection.aggregate( [
{ $facet:
{
<outputField1>: [ { <stage1> }, { <stage2> }, ... ],
<outputField2>: [ { <stage1> }, { <stage2> }, ... ],
...
}
}
] )

Facet-related aggregation stages ($bucket, $bucketAuto, $sortByCount)


can be used in sub-pipelines for multi-faceted aggregations. All other aggregation
stages can also be used in sub-pipelines, with the following exceptions: $facet,
$out, $geoNear, $indexStats, $collStats.

F O R M O R E I N F O R M AT I O N

https://docs.mongodb.com/manual/aggregation/
I N DEXI NG
I N DEXI NG

Index Creation Syntax


db.coll.createIndex(key_pattern, options)
Creates an index on collection coll with given key pattern and options.

I N D E X I N G K E Y PAT T E R N S

Simple index on field a , or a


multikey index on an array a; it is
{a:1}
not necessar y to explicitly specif y
the multikey t ype for arrays .

Compound index with a ascending


{a:1, b:-1}
and b descending.

Ascending index on embedded


{"a.b": 1}
f i e l d "a.b".

Te x t i n d e x o n f i e l d a . A c o l l e c t i o n
{a: "text"}
can have at most one tex t index .

Geospatial index where the a


field stores GeoJSON data . See
{a: "2dsphere"}
documentation for valid GeoJSON
format ting.

Hashed index on field a . Generally


{a: "hashed"}
used with hash-based sharding.

INDEX OPTIONS:

Create an index that requires all


{unique: true} values of the indexed field to be
unique.

Create this index in the


background; useful when you
{background: true}
need to minimize index creation
per formance impact .
Specif y a custom name for this
index . If not specified,
{name: "foo"}
the name will be derived from the
key pat tern .

Create a time to live ( T TL) index


o n t h e i n d e x k e y. T h i s w i l l f o r c e
{expireAfterSeconds:3600 } the system to drop the document
a f t e r 360 0 s e c o n d s e x p i r e . O n l y
w o r k s o n k e y s o f d ate t y p e .

Use with tex t indexes to define


{default_language:
the default language used for stop
'portuguese'} words and stemming.

Par tial indexes only index the


documents in a collection that
{partialFilterExpression: { meet a specified filter expression
h e r e , w h e r e r ati n g.g r a d e i s
'rating.grade': { $gte: 60 }
g r e a t e r t h a n 60 . P a r t i a l i n d e x e s
}} will only be used by queries that
contain the filter expression or a
subset thereof.

EXAMPLES:

db.products.createIndex(
{'supplier':1}, Creates ascending index on
{unique:true} su p plie r a s s u r i n g u n i q u e v a l u e s .
)

db.products.createIndex(
{'description': 'text', Creates tex t index on
{'default_language': d e sc rip tio n k e y u s i n g
'spanish'} S p a n ish f o r s t e m m i n g .
)

INDEXING
Creates a compound index that
db.products.createIndex( indexes only the document s
{style: 1, name: 1}, with a rating field greater
{partialFilterExpression: t h a n 5 . Yo u c a n s p e c i f y a
{rating: { $gt: 5}}} p a r tia lFilt e rE x p r e ssio n
) option for all MongoDB index
types.

db.stores.createIndex(
C r e a t e s a 2d sp h e r e g e o s p a t i a l
{location: "2dsphere"}
i n d e x o n lo c atio n k e y.
)

A D M I N I S T R AT I O N

Get s a list of all indexes on the


db.products.getIndexes()
p r o d u c ts c o l l e c t i o n .

Rebuilds all indexes on this


db.products.reIndex()
collection.

Drops the index with key


p a t t e r n {x: 1, y: -1}.
U s e d b.pr o d u c ts.
db.products.dropIndex({x: 1, d r o pIn d e x('i n d e x _ a') t o
y: -1}) drop index named index_a . Use
d b.pr o d u c ts.d r o pIn d e xe s()
to drop all indexes on the
products collection.

F O R M O R E I N F O R M AT I O N

https://docs.mongodb.com/manual/indexes/

INDEXING
D O C U M E N T VA L I D AT I O N
W H AT I S D O C U M E N T VA L I D AT I O N ?

MongoDB provides the capabilit y to validate documents during updates and inser ts.
Validation rules are specified per collection using the validator option.

EXAMPLE

Add document validation to an existing collection using the collMod


command with the validator option or when creating a new collection using
db.createCollection():

db.createCollection( "contacts",
{ validator: { $or:
[
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
},
validationLevel: "moderate"
validationAction: "warn"
} )

MongoDB also provides the validationLevel option, which determines how


strictly MongoDB applies validation rules to existing documents during an update,
and the validationAction option, which determines whether MongoDB should
error and reject documents that violate the validation rules or warn about the
violations in the log but allow invalid documents.

F O R M O R E I N F O R M AT I O N

https://docs.mongodb.com/manual/core/document-validation/
VI EWS
W H AT A R E V I E W S ?

Views are of ten used in relational databases to achieve both data securit y and a
high level of abstraction, making it easier to retrieve data . Unlike regular tables,
MongoDB views neither have a physical schema nor use disk space.

MongoDB views execute a pre-specified quer y. To create a view, use the


db.createView('view_name','source',[pipeline]) command, specif ying
the view name, the view source collection, and an aggregation pipeline that defines
the view. This aggregation pipeline, as well as the other parameters, is saved in
the system.views collection. This is the only space that the view will use in the
system. A new document is saved in the system.views collection for each view
created.

F O R M O R E I N F O R M AT I O N

https://docs.mongodb.com/manual/core/views/
R E P L I C AT I O N
R E P L I C AT I O N

A replica set in MongoDB is a group of mongod processes that maintain the same
data set . Replica sets provide redundancy and high availabilit y, and are the basis for
all production deployments. Replication of data is handled automatically, and in the
event of node failure or net work par tition, an automatic failover occurs.

SETUP:

Deploying a replica set for development or testing is a simple process. The example
setup below should not be used for production; for instance, this setup involves
only a single ser ver, while a production environment should involve separate ser vers
in different physical locations for high availabilit y. See the documentation for
production instructions.

The basic procedure is to star t the mongod instances that will become members of
the replica set , configure the replica set itself, and then add the mongod instances
to it .

Before deploying a replica set , MongoDB must already be installed on each system
that will be par t of the replica set . Ensure that your net work configuration allows all
possible connections bet ween each member.

E X A M P L E S E T U P, 3 - M E M B E R R E P L I CA S E T

1. Create data directories for each member with a command similar to the following.
mkdir -p /srv/mongodb/rs0-0 /srv/mongodb/rs0-1 /srv/mongodb/rs0-2

2. Star t 3 mongod instances in their own shell windows with a command similar to
the following. These commands star t each mongod as a member of a replica set
named rs0, each with a distinct por t; if you are already using these por ts, select
different ones.
1. mongod --port 27017 --dbpath /srv/mongodb/rs0-0 --replSet rs0
2. mongod --port 27018 --dbpath /srv/mongodb/rs0-1 --replSet rs0
3. mongod --port 27019 --dbpath /srv/mongodb/rs0-2 --replSet rs0
3. Connect to any mongod instance through the mongo shell. Here, we connect to
the first mongod created.
mongo --port 27017

4. While connected, use the command below to initiate a replica set . As writ ten
below, default configuration will be used. See the documentation for how to
include a configuration document when initializing.
rs.initiate()

5. In the same mongo shell, add the t wo remaining mongod to the replica set
using the commands below.
rs.add( "rs0-1:27018" )
rs.add( "rs0-2:27019" )

6. The three-member replica is now running. At any time, use rs.conf() to check
the replica set configuration or rs.status() to check the status.

A D M I N I S T R AT I O N :

Create a new replica set with one


rs.initiate()
m e m b e r.

rs.add("host:port") A d d a m e m b e r.

rs.addArb("host:port") A d d a n a r b i t e r.

rs.remove("host:port") R e m o v e a m e m b e r.

Returns a document with


rs.status() information about the state of the
replica set .

R E P L I C AT I O N
Returns the replica set
rs.conf()
configuration document .

Re-configures a replica set


rs.reconfig(newConfig) by applying a new replica set
configuration object .

rs.isMaster() S e e w h i c h m e m b e r i s p r i m a r y.

Force the primar y to become a


secondar y for n seconds, during
rs.stepDown(n)
which time an elec tion c an t ake
place.

Prevent the current member from


rs.freeze(n) seeking election as primar y for n
seconds . n=0 means unfreeze .

Prints a repor t of the status of the


rs.printSlave ReplicationInfo() replica set from the perspective of
the secondaries.

F O R M O R E I N F O R M AT I O N

https://docs.mongodb.com/manual/replication/

R E P L I C AT I O N
S HAR DI NG
W H AT I S S H A R D I N G ?

Sharding is a method for distributing data across multiple machines. MongoDB uses
sharding to suppor t deployments with ver y large data sets and high throughput
operations.

Database systems with large data sets or high throughput applications can
challenge the capacit y of a single ser ver. For example, high quer y rates can exhaust
the CPU capacit y of the ser ver. Working set sizes larger than the systems R AM
stress the I/O capacit y of disk drives.

There are t wo methods for addressing system grow th: ver tical and horizontal
scaling.

V E R T I C A L S C A LI N G

Ver tical Scaling involves increasing the capacit y of a single ser ver, such as using
a more power ful CPU, adding more R AM, or increasing the amount of storage
space. Limitations in available technology may restrict a single machine from being
sufficiently power ful for a given workload. Additionally, Cloud-based providers have
hard ceilings based on available hardware configurations. As a result , there is a
practical ma ximum for ver tical scaling.

H O R I ZO N TA L S C A LI N G

Horizontal Scaling involves dividing the system dataset and load over multiple
ser vers, adding additional ser vers to increase capacit y as required. While the overall
speed or capacit y of a single machine may not be high, each machine handles a
subset of the overall workload, potentially providing bet ter efficiency than a single
high-speed high-capacit y ser ver. Expanding the capacit y of the deployment only
requires adding additional ser vers as needed, which can be a lower overall cost
than high-end hardware for a single machine. The trade off is increased complexit y
in infrastructure and maintenance for the deployment .

MongoDB suppor ts horizontal scaling through sharding.


sh.enableSharding( E n a b l e s h a r d i n g o n p r o d u c ts
"products") database.

S h a r d c o l l e c t i o n c at a lo g o f
p r o d u c ts d a t a b a s e w i t h s h a r d
k e y c o n s i s t i n g o f t h e sk u a n d
brand fields . This is an example
of range-based sharding. Range-
sh.shardCollection( based sharding involves dividing
data into contiguous ranges
"products.catalog",
determined by the shard key
{ sku:1, brand:1 } values. In this model, documents
) w i t h " c l o s e" s h a r d k e y v a l u e s a r e
likely to be in the same chunk or
shard. This allows for efficient
queries where reads target
documents within a contiguous
range.

S h a r d c o l l e c t i o n c at a lo g o f
p r o d u c ts d a t a b a s e w i t h s h a r d
key consisting of a hash of the
_ id f i e l d . T h i s i s a n e x a m p l e o f
hashed sharding. Use hashed
sh.shardCollection( sharding for collections that do
not naturally contain a key that
"products.collection",
will ensure an even distribution
{ _id : "hashed" } of documents across shards.
) Hashing offers even distribution
of data at the likely expense of
more broadcast operations. Uses
a hashed index of a single field
as the shard key to par tition data
a c r o s s y o u r s h a r d e d c l u s t e r.

SHARDING
Print a format ted repor t of the
sharding configuration and the
sh.status()
information regarding existing
chunks in a sharded cluster

Adds existing replica set


sh.addShard( 'REPLICA1/
R E P LIC A 1 a s a s h a r d t o t h e
host:27017')
c l u s t e r.

F O R M O R E I N F O R M AT I O N

https://docs.mongodb.com/manual/sharding/

SHARDING
M A P P I N G S Q L TO M O N G O D B
M A P P I N G S Q L TO M O N G O D B

CONVE RTI NG TO MONGOD B TE R M S

M Y S Q L E X E C U TA B L E O R A C L E E X E C U TA B L E M O N G O D B E X E C U TA B L E

mysqld oracle mongod

mysql sqlplus mongo

SQL TERM MONGODB TERM

database (schema) database

table collection

index index

row document

column field

joining linking & embedding

F O R M O R E I N F O R M AT I O N
partition shard
https://docs.mongodb.com/manual/core/document-validation/
Queries and other operations in MongoDB are represented as documents passed
to find and other methods. Below are examples of SQL statements and the
analogous statements in MongoDB JavaScript shell synta x.

SQL MONGODB

CREATE TABLE people (


id MEDIUMINT NOT NULL
AUTO_INCREMENT, user_id d b . p e o p l e . i n s e r t O n e ( { u s e r_ i d :
Varchar(30), age Number, " a b c12 3 ", a g e : 5 5 , s t a t u s : "A" } )
status char(1), PRIMARY KEY
(id) )

ALTER TABLE people ADD join_ db.people.updateMany( { }, { $set:


date DATETIME { join_date: new Date( ) } } )

ALTER TABLE people DROP db.people.updateMany( { }, {


COLUMN join_date $ u n s e t : { " j o i n _ d a t e ": " " } } )

CREATE INDEX idx_user_id_asc d b . p e o p l e . c r e a t e I n d e x ( { u s e r_ i d :


ON people(user_id) 1 } )

CREATE INDEX idx_user_id_


d b . p e o p l e . c r e a t e I n d e x ( { u s e r_ i d :
asc_age_desc ON people(user_
1, a g e : -1 } )
id, age DESC)

DROP TABLE people db.people.drop( )

INSERT INTO people(user_


d b . p e o p l e . i n s e r t O n e ( { u s e r_ i d :
id, age, status) VALUES
" b c d 0 01", a g e : 4 5 , s t a t u s : "A" } )
("bcd001", 45, "A")

SELECT * FROM people db.people.find( )

MAPPING SQL
SELECT id, user_id, status d b . p e o p l e . f i n d ( { } , { u s e r_ i d : 1,
FROM people st atus: 1 } )

SELECT user_id, status FROM d b . p e o p l e . f i n d ( { } , { u s e r_ i d : 1,


people s t a t u s : 1, _ i d : 0 } )

SELECT * FROM people WHERE


d b . p e o p l e . f i n d ( { s t a t u s : "A" } )
status = "A"

SELECT user_id, status FROM d b . p e o p l e . f i n d ( { s t a t u s : "A" } , {


people WHERE status = "A" u s e r_ i d : 1, s t a t u s : 1, _ i d : 0 } )

SELECT * FROM people WHERE d b . p e o p l e . f i n d ( { s t a t u s : { $ n e : "A"


status != "A"' } } )

SELECT * FROM people WHERE d b . p e o p l e . f i n d ( { s t a t u s : "A", a g e :


status = "A" AND age = 50 50 } )

SELECT * FROM people WHERE db.people.find( { $or: [ { st atus:


status = "A" OR age = 50 "A" } , { a g e : 5 0 } ] } )

SELECT * FROM people WHERE db.people.find( { age: { $gt: 25 }


age > 25 } )

SELECT * FROM people WHERE


db.people.find( { age: { $lt: 25 } } )
age < 25

SELECT * FROM people WHERE db.people.find( { age: { $gt: 25,


age > 25 AND age <= 50 $lte: 50 } } )

SELECT * FROM people WHERE


d b . p e o p l e . f i n d ( { u s e r_ i d : / b c / } )
user_id like "%bc%"

MAPPING SQL
SELECT * FROM people WHERE d b . p e o p l e . f i n d ( { u s e r_ i d : { $ r e g e x :
user_id like "bc%" /^b c / } } )

SELECT * FROM people WHERE


d b . p e o p l e . f i n d ( { s t a t u s : "A" }
status = "A" ORDER BY user_
) . s o r t ( { u s e r_ i d : 1 } )
id ASC
SELECT * FROM people WHERE
d b . p e o p l e . f i n d ( { s t a t u s : "A" }
status = "A" ORDER BY user_
) . s o r t ( { u s e r_ i d : -1 } )
id DESC

SELECT COUNT(*) FROM people db.people.count( )

SELECT COUNT(user_id) FROM d b . p e o p l e . c o u n t ( { u s e r_ i d : {


people $exist s: true } } )

SELECT COUNT(*) FROM people db.people.count( { age: { $gt: 30


WHERE age > 30 } } )

SELECT DISTINCT(status) FROM


d b . p e o p l e . d i s t i n c t ( " s t a t u s" )
people

SELECT * FROM people LIMIT 1 db.people.findOne( )

SELECT * FROM people LIMIT 5


d b . p e o p l e . f i n d ( ) . l i m i t ( 5) . s k i p (10)
SKIP 10

EXPLAIN SELECT * FROM people d b . p e o p l e . f i n d ( { s t a t u s : "A" }


WHERE status = "A" ).explain( )

db.people.updateMany( { age: {
UPDATE people SET status =
$gt: 25 } }, { $set: { st atus: "C" }
"C" WHERE age > 25
} )

MAPPING SQL
UPDATE people SET age = age db.people.updateMany ( { st atus:
+ 3 WHERE status = "A" "A" } , { $ i n c : { a g e : 3 } } )

DELETE FROM people WHERE db.people.deleteMany ( { st atus:


status = "D" "D" } )

DELETE FROM people db.people.deleteMany( { } )

F O R M O R E I N F O R M AT I O N

http://docs.mongodb.org/manual/reference/sql-comparison/

MAPPING SQL
R E SOU RCE S
LEARN

Downloads - mongodb.com/download-center
Enterprise Advanced - mongodb.com/enterprise
MongoDB Manual - docs.mongodb.com
Free Online Education - university.mongodb.com
Presentations - mongodb.com/presentations
In-person Training - university.mongodb.com/training

SUPPORT

Stack Over flow - stackoverflow.com/questions/tagged/mongodb


Google Group - groups.google.com/group/mongodb-user
Bug Tracking - jira.mongodb.org
MongoDB Management Ser vice - m ms.mongodb.com
Commercial Suppor t - mongodb.com/support

COMMUNITY

MongoDB User Groups (MUGs) - mongodb.com/user-groups


MongoDB Events - mongodb.com/events

SOCIAL

Twit ter - @MongoDB


Facebook - facebook.com/mongodb
LinkedIn - linkedin.com/groups/MongoDB-2340731

C O N TA C T

Contact MongoDB - mongodb.com/contact


T H E D ATA B A S E A S A S E R V I C E

F R O M T H E T E A M T H AT B U I L D S M O N G O D B

The best way to deploy, operate,


and scale mongoDB in the cloud.

G E T S TA R T E D F O R F R E E A T MONGODB.COM/ATLAS

S-ar putea să vă placă și