Documente Academic
Documente Profesional
Documente Cultură
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 ?
The following table lists some common help commands which are available in the
mongo shell:
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.
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
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:
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".
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".
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
A R R AY U P D A T E O P E R A T O R S
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.
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:
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}
Deconstructs array
{ a : [2 , 3 , 4] } => { a : 2 } ,
{$unwind: "$a"} field a into individual
{a:3}, {a:4}
documents of each.
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.
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.
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.
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> }, ... ],
...
}
}
] )
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
I N D E X I N G K E Y PAT T E R N S
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 .
INDEX OPTIONS:
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
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
db.createCollection( "contacts",
{ validator: { $or:
[
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
},
validationLevel: "moderate"
validationAction: "warn"
} )
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.
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 :
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.
R E P L I C AT I O N
Returns the replica set
rs.conf()
configuration document .
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.
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 .
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
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
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
table collection
index index
row document
column field
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
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 } )
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 / } } )
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 } } )
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
COMMUNITY
SOCIAL
C O N TA C T
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
G E T S TA R T E D F O R F R E E A T MONGODB.COM/ATLAS