MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet...

79
MongoDB #mongodb

Transcript of MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet...

Page 1: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

MongoDB

mongodb

1

1 MongoDB 2

2

2

Examples 2

2

5

5

MongoDB JavaScript 5

6

6

2 2dsphere 8

Examples 8

2dsphere 8

3 CRUD 9

9

9

Examples 9

9

9

10

10

11

multi 11

12

4 MongoDB - TLS SSL ReplicaSet 13

13

Examples 13

TLS SSL ReplicaSet 13

13

13

13

14

ReplicaSet 14

SSL ReplicaSet 14

(Mongo Shell) ReplicaSet 15

SSL 15

SSL 15

5 MongoDB 17

Examples 17

17

6 MongoDB 18

18

18

Examples 18

apt 1604 34 18

7 MongoDB 19

19

Examples 19

19

8 MongoDB 20

Examples 20

20

Java Spring 23

25

($ Lookup) 25

9 MongoDB 26

26

Examples 26

26

10 Pluggable Storage Engine 27

27

Examples 27

MMAP 27

WiredTiger 27

WiredTiger 27

27

27

- io 27

TokuMX 28

11 Upserts 29

Examples 29

29

12 30

30

Examples 31

mongo 32

13 33

33

Examples 33

33

14 35

Examples 35

JSON mongoimport 35

CSV mongoimport 35

15 37

Examples 37

mongod mongodump 37

mongod mongorestore 37

16 () 38

38

Examples 38

() 38

FindOne () 38

- AND OR IN 38

find () 41

Find () 41

find () 41

17 44

Examples 44

44

44

18 45

Examples 45

3 45

19 47

Examples 47

Mongodb 47

20 49

Examples 49

MongoDB Replica Set 49

21 51

51

51

Examples 51

51

51

51

51

51

53

53

54

54

54

22 56

Examples 56

56

23 57

57

57

57

Examples 57

$ set 57

I 57

57

III $ 58

24 60

Examples 60

60

60

60

25 62

62

62

62

62

Examples 62

62

63

64

64

64

( ) 65

26 67

67

Examples 67

67

68

27 69

69

69

Examples 69

pymongo MongoDB 69

PyMongo 69

PyMongo 70

71

You can share this PDF with anyone you feel could benefit from it downloaded the latest version from mongodb

It is an unofficial and free MongoDB ebook created for educational purposes All the content is extracted from Stack Overflow Documentation which is written by many hardworking individuals at Stack Overflow It is neither affiliated with Stack Overflow nor official MongoDB

The content is released under Creative Commons BY-SA and the list of contributors to each chapter are provided in the credits section at the end of this book Images may be copyright of their respective owners unless otherwise specified All trademarks and registered trademarks are the property of their respective company owners

Use the content presented in this book at your own risk it is not guaranteed to be correct nor accurate please send your feedback and corrections to infozzzprojectscom

httpsriptutorialcomkohome 1

1 MongoDB SQL NoSQL bullMongoDB NoSQL JSON JSON MongoDB bullMongoDB - mongod mongo bullv32 MongoDB Mongo javascript $ lookup javascript bullOperations Checklist bull

34 2016-11-29

32 2015-12-08

30 2015-03-03

26 2014-04-08

24 2013-03-19

22 2012-08-29

20 2011-09-12

18 2011-03-16

16 2010-08-31

14 2010-03-25

12 2009-12-10

Examples

MongoDB

Mac OS

Mac OS (homebrew)

homebrew

$ brew install mongodb

32 64 tgz

bull

httpsriptutorialcomkohome 2

$ tar xvf mongodb-osx-xyztgz

xyz tgz bin mongod mongo

datadb

$ sudo bash mkdir -p datadb chmod 777 data chmod 777 datadb exit

$ mongod

27017

$ mongo

test connecting to test connecting to test MongoDB Hello World

Windows

32 64

exe

mongodb CProgram FilesMongoDBServer32bin 32

bin mongod mongo

bull

httpsriptutorialcomkohome 3

Windows 10 Windows 10

db data

cmd Shift Ctrl GUI

gt mongod

27017

gt mongo

test connecting to test connecting to test MongoDB Hello World

Linux Mac OS

( apt-get )

MongoDB

$ sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv EA312927 gpg Total number processed 1 gpg imported 1 (RSA 1)

1604

$ echo deb httprepomongodborgaptubuntu xenialmongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

1404

$ echo deb httprepomongodborgaptubuntu trustymongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

$ sudo apt-get update

MongoDB

$ sudo apt-get install mongodb-org

Red Hat ( yum )

bull

httpsriptutorialcomkohome 4

$ vi etcyumreposdmongodb-org-34repo

[mongodb-org-34] name=MongoDB Repository baseurl=httpsrepomongodborgyumredhat$releasevermongodb-org34x86_64 gpgcheck=1 enabled=1 gpgkey=httpswwwmongodborgstaticpgpserver-34asc

$ sudo yum update

MongoDB

$ sudo yum install mongodb-org

mongo shell ( )

gt dbworldinsert( speech Hello World ) gt cur = dbworldfind()x=curnext()print(x[speech])

test world key value bull cur javascript next() x js bull

SQL MongoDB

(mongodb _id )

MongoDB JavaScript

mongo localhost27017mydb myjsfilejs

httpsriptutorialcomkohome 5

myjsfilejs A mongo mydb mongod localhost 27017 localhost27017 mongodb

mongo js

gtload(myjsfilejs)

gt dbtestinsert(keyvalue1key2Val2key3val3) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue2key2Val21key3val31) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue3key2Val22key3val33) WriteResult( nInserted 1 )

gt dbtestfind() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val2 1 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val2 2 key3 val33

pretty ()

gt dbtestfind()pretty() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val21 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val22 key3 val33 gt

show dbs

( mydb mydb

httpsriptutorialcomkohome 6

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 2: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

1

1 MongoDB 2

2

2

Examples 2

2

5

5

MongoDB JavaScript 5

6

6

2 2dsphere 8

Examples 8

2dsphere 8

3 CRUD 9

9

9

Examples 9

9

9

10

10

11

multi 11

12

4 MongoDB - TLS SSL ReplicaSet 13

13

Examples 13

TLS SSL ReplicaSet 13

13

13

13

14

ReplicaSet 14

SSL ReplicaSet 14

(Mongo Shell) ReplicaSet 15

SSL 15

SSL 15

5 MongoDB 17

Examples 17

17

6 MongoDB 18

18

18

Examples 18

apt 1604 34 18

7 MongoDB 19

19

Examples 19

19

8 MongoDB 20

Examples 20

20

Java Spring 23

25

($ Lookup) 25

9 MongoDB 26

26

Examples 26

26

10 Pluggable Storage Engine 27

27

Examples 27

MMAP 27

WiredTiger 27

WiredTiger 27

27

27

- io 27

TokuMX 28

11 Upserts 29

Examples 29

29

12 30

30

Examples 31

mongo 32

13 33

33

Examples 33

33

14 35

Examples 35

JSON mongoimport 35

CSV mongoimport 35

15 37

Examples 37

mongod mongodump 37

mongod mongorestore 37

16 () 38

38

Examples 38

() 38

FindOne () 38

- AND OR IN 38

find () 41

Find () 41

find () 41

17 44

Examples 44

44

44

18 45

Examples 45

3 45

19 47

Examples 47

Mongodb 47

20 49

Examples 49

MongoDB Replica Set 49

21 51

51

51

Examples 51

51

51

51

51

51

53

53

54

54

54

22 56

Examples 56

56

23 57

57

57

57

Examples 57

$ set 57

I 57

57

III $ 58

24 60

Examples 60

60

60

60

25 62

62

62

62

62

Examples 62

62

63

64

64

64

( ) 65

26 67

67

Examples 67

67

68

27 69

69

69

Examples 69

pymongo MongoDB 69

PyMongo 69

PyMongo 70

71

You can share this PDF with anyone you feel could benefit from it downloaded the latest version from mongodb

It is an unofficial and free MongoDB ebook created for educational purposes All the content is extracted from Stack Overflow Documentation which is written by many hardworking individuals at Stack Overflow It is neither affiliated with Stack Overflow nor official MongoDB

The content is released under Creative Commons BY-SA and the list of contributors to each chapter are provided in the credits section at the end of this book Images may be copyright of their respective owners unless otherwise specified All trademarks and registered trademarks are the property of their respective company owners

Use the content presented in this book at your own risk it is not guaranteed to be correct nor accurate please send your feedback and corrections to infozzzprojectscom

httpsriptutorialcomkohome 1

1 MongoDB SQL NoSQL bullMongoDB NoSQL JSON JSON MongoDB bullMongoDB - mongod mongo bullv32 MongoDB Mongo javascript $ lookup javascript bullOperations Checklist bull

34 2016-11-29

32 2015-12-08

30 2015-03-03

26 2014-04-08

24 2013-03-19

22 2012-08-29

20 2011-09-12

18 2011-03-16

16 2010-08-31

14 2010-03-25

12 2009-12-10

Examples

MongoDB

Mac OS

Mac OS (homebrew)

homebrew

$ brew install mongodb

32 64 tgz

bull

httpsriptutorialcomkohome 2

$ tar xvf mongodb-osx-xyztgz

xyz tgz bin mongod mongo

datadb

$ sudo bash mkdir -p datadb chmod 777 data chmod 777 datadb exit

$ mongod

27017

$ mongo

test connecting to test connecting to test MongoDB Hello World

Windows

32 64

exe

mongodb CProgram FilesMongoDBServer32bin 32

bin mongod mongo

bull

httpsriptutorialcomkohome 3

Windows 10 Windows 10

db data

cmd Shift Ctrl GUI

gt mongod

27017

gt mongo

test connecting to test connecting to test MongoDB Hello World

Linux Mac OS

( apt-get )

MongoDB

$ sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv EA312927 gpg Total number processed 1 gpg imported 1 (RSA 1)

1604

$ echo deb httprepomongodborgaptubuntu xenialmongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

1404

$ echo deb httprepomongodborgaptubuntu trustymongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

$ sudo apt-get update

MongoDB

$ sudo apt-get install mongodb-org

Red Hat ( yum )

bull

httpsriptutorialcomkohome 4

$ vi etcyumreposdmongodb-org-34repo

[mongodb-org-34] name=MongoDB Repository baseurl=httpsrepomongodborgyumredhat$releasevermongodb-org34x86_64 gpgcheck=1 enabled=1 gpgkey=httpswwwmongodborgstaticpgpserver-34asc

$ sudo yum update

MongoDB

$ sudo yum install mongodb-org

mongo shell ( )

gt dbworldinsert( speech Hello World ) gt cur = dbworldfind()x=curnext()print(x[speech])

test world key value bull cur javascript next() x js bull

SQL MongoDB

(mongodb _id )

MongoDB JavaScript

mongo localhost27017mydb myjsfilejs

httpsriptutorialcomkohome 5

myjsfilejs A mongo mydb mongod localhost 27017 localhost27017 mongodb

mongo js

gtload(myjsfilejs)

gt dbtestinsert(keyvalue1key2Val2key3val3) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue2key2Val21key3val31) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue3key2Val22key3val33) WriteResult( nInserted 1 )

gt dbtestfind() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val2 1 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val2 2 key3 val33

pretty ()

gt dbtestfind()pretty() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val21 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val22 key3 val33 gt

show dbs

( mydb mydb

httpsriptutorialcomkohome 6

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 3: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

13

14

ReplicaSet 14

SSL ReplicaSet 14

(Mongo Shell) ReplicaSet 15

SSL 15

SSL 15

5 MongoDB 17

Examples 17

17

6 MongoDB 18

18

18

Examples 18

apt 1604 34 18

7 MongoDB 19

19

Examples 19

19

8 MongoDB 20

Examples 20

20

Java Spring 23

25

($ Lookup) 25

9 MongoDB 26

26

Examples 26

26

10 Pluggable Storage Engine 27

27

Examples 27

MMAP 27

WiredTiger 27

WiredTiger 27

27

27

- io 27

TokuMX 28

11 Upserts 29

Examples 29

29

12 30

30

Examples 31

mongo 32

13 33

33

Examples 33

33

14 35

Examples 35

JSON mongoimport 35

CSV mongoimport 35

15 37

Examples 37

mongod mongodump 37

mongod mongorestore 37

16 () 38

38

Examples 38

() 38

FindOne () 38

- AND OR IN 38

find () 41

Find () 41

find () 41

17 44

Examples 44

44

44

18 45

Examples 45

3 45

19 47

Examples 47

Mongodb 47

20 49

Examples 49

MongoDB Replica Set 49

21 51

51

51

Examples 51

51

51

51

51

51

53

53

54

54

54

22 56

Examples 56

56

23 57

57

57

57

Examples 57

$ set 57

I 57

57

III $ 58

24 60

Examples 60

60

60

60

25 62

62

62

62

62

Examples 62

62

63

64

64

64

( ) 65

26 67

67

Examples 67

67

68

27 69

69

69

Examples 69

pymongo MongoDB 69

PyMongo 69

PyMongo 70

71

You can share this PDF with anyone you feel could benefit from it downloaded the latest version from mongodb

It is an unofficial and free MongoDB ebook created for educational purposes All the content is extracted from Stack Overflow Documentation which is written by many hardworking individuals at Stack Overflow It is neither affiliated with Stack Overflow nor official MongoDB

The content is released under Creative Commons BY-SA and the list of contributors to each chapter are provided in the credits section at the end of this book Images may be copyright of their respective owners unless otherwise specified All trademarks and registered trademarks are the property of their respective company owners

Use the content presented in this book at your own risk it is not guaranteed to be correct nor accurate please send your feedback and corrections to infozzzprojectscom

httpsriptutorialcomkohome 1

1 MongoDB SQL NoSQL bullMongoDB NoSQL JSON JSON MongoDB bullMongoDB - mongod mongo bullv32 MongoDB Mongo javascript $ lookup javascript bullOperations Checklist bull

34 2016-11-29

32 2015-12-08

30 2015-03-03

26 2014-04-08

24 2013-03-19

22 2012-08-29

20 2011-09-12

18 2011-03-16

16 2010-08-31

14 2010-03-25

12 2009-12-10

Examples

MongoDB

Mac OS

Mac OS (homebrew)

homebrew

$ brew install mongodb

32 64 tgz

bull

httpsriptutorialcomkohome 2

$ tar xvf mongodb-osx-xyztgz

xyz tgz bin mongod mongo

datadb

$ sudo bash mkdir -p datadb chmod 777 data chmod 777 datadb exit

$ mongod

27017

$ mongo

test connecting to test connecting to test MongoDB Hello World

Windows

32 64

exe

mongodb CProgram FilesMongoDBServer32bin 32

bin mongod mongo

bull

httpsriptutorialcomkohome 3

Windows 10 Windows 10

db data

cmd Shift Ctrl GUI

gt mongod

27017

gt mongo

test connecting to test connecting to test MongoDB Hello World

Linux Mac OS

( apt-get )

MongoDB

$ sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv EA312927 gpg Total number processed 1 gpg imported 1 (RSA 1)

1604

$ echo deb httprepomongodborgaptubuntu xenialmongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

1404

$ echo deb httprepomongodborgaptubuntu trustymongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

$ sudo apt-get update

MongoDB

$ sudo apt-get install mongodb-org

Red Hat ( yum )

bull

httpsriptutorialcomkohome 4

$ vi etcyumreposdmongodb-org-34repo

[mongodb-org-34] name=MongoDB Repository baseurl=httpsrepomongodborgyumredhat$releasevermongodb-org34x86_64 gpgcheck=1 enabled=1 gpgkey=httpswwwmongodborgstaticpgpserver-34asc

$ sudo yum update

MongoDB

$ sudo yum install mongodb-org

mongo shell ( )

gt dbworldinsert( speech Hello World ) gt cur = dbworldfind()x=curnext()print(x[speech])

test world key value bull cur javascript next() x js bull

SQL MongoDB

(mongodb _id )

MongoDB JavaScript

mongo localhost27017mydb myjsfilejs

httpsriptutorialcomkohome 5

myjsfilejs A mongo mydb mongod localhost 27017 localhost27017 mongodb

mongo js

gtload(myjsfilejs)

gt dbtestinsert(keyvalue1key2Val2key3val3) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue2key2Val21key3val31) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue3key2Val22key3val33) WriteResult( nInserted 1 )

gt dbtestfind() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val2 1 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val2 2 key3 val33

pretty ()

gt dbtestfind()pretty() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val21 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val22 key3 val33 gt

show dbs

( mydb mydb

httpsriptutorialcomkohome 6

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 4: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

Examples 27

MMAP 27

WiredTiger 27

WiredTiger 27

27

27

- io 27

TokuMX 28

11 Upserts 29

Examples 29

29

12 30

30

Examples 31

mongo 32

13 33

33

Examples 33

33

14 35

Examples 35

JSON mongoimport 35

CSV mongoimport 35

15 37

Examples 37

mongod mongodump 37

mongod mongorestore 37

16 () 38

38

Examples 38

() 38

FindOne () 38

- AND OR IN 38

find () 41

Find () 41

find () 41

17 44

Examples 44

44

44

18 45

Examples 45

3 45

19 47

Examples 47

Mongodb 47

20 49

Examples 49

MongoDB Replica Set 49

21 51

51

51

Examples 51

51

51

51

51

51

53

53

54

54

54

22 56

Examples 56

56

23 57

57

57

57

Examples 57

$ set 57

I 57

57

III $ 58

24 60

Examples 60

60

60

60

25 62

62

62

62

62

Examples 62

62

63

64

64

64

( ) 65

26 67

67

Examples 67

67

68

27 69

69

69

Examples 69

pymongo MongoDB 69

PyMongo 69

PyMongo 70

71

You can share this PDF with anyone you feel could benefit from it downloaded the latest version from mongodb

It is an unofficial and free MongoDB ebook created for educational purposes All the content is extracted from Stack Overflow Documentation which is written by many hardworking individuals at Stack Overflow It is neither affiliated with Stack Overflow nor official MongoDB

The content is released under Creative Commons BY-SA and the list of contributors to each chapter are provided in the credits section at the end of this book Images may be copyright of their respective owners unless otherwise specified All trademarks and registered trademarks are the property of their respective company owners

Use the content presented in this book at your own risk it is not guaranteed to be correct nor accurate please send your feedback and corrections to infozzzprojectscom

httpsriptutorialcomkohome 1

1 MongoDB SQL NoSQL bullMongoDB NoSQL JSON JSON MongoDB bullMongoDB - mongod mongo bullv32 MongoDB Mongo javascript $ lookup javascript bullOperations Checklist bull

34 2016-11-29

32 2015-12-08

30 2015-03-03

26 2014-04-08

24 2013-03-19

22 2012-08-29

20 2011-09-12

18 2011-03-16

16 2010-08-31

14 2010-03-25

12 2009-12-10

Examples

MongoDB

Mac OS

Mac OS (homebrew)

homebrew

$ brew install mongodb

32 64 tgz

bull

httpsriptutorialcomkohome 2

$ tar xvf mongodb-osx-xyztgz

xyz tgz bin mongod mongo

datadb

$ sudo bash mkdir -p datadb chmod 777 data chmod 777 datadb exit

$ mongod

27017

$ mongo

test connecting to test connecting to test MongoDB Hello World

Windows

32 64

exe

mongodb CProgram FilesMongoDBServer32bin 32

bin mongod mongo

bull

httpsriptutorialcomkohome 3

Windows 10 Windows 10

db data

cmd Shift Ctrl GUI

gt mongod

27017

gt mongo

test connecting to test connecting to test MongoDB Hello World

Linux Mac OS

( apt-get )

MongoDB

$ sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv EA312927 gpg Total number processed 1 gpg imported 1 (RSA 1)

1604

$ echo deb httprepomongodborgaptubuntu xenialmongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

1404

$ echo deb httprepomongodborgaptubuntu trustymongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

$ sudo apt-get update

MongoDB

$ sudo apt-get install mongodb-org

Red Hat ( yum )

bull

httpsriptutorialcomkohome 4

$ vi etcyumreposdmongodb-org-34repo

[mongodb-org-34] name=MongoDB Repository baseurl=httpsrepomongodborgyumredhat$releasevermongodb-org34x86_64 gpgcheck=1 enabled=1 gpgkey=httpswwwmongodborgstaticpgpserver-34asc

$ sudo yum update

MongoDB

$ sudo yum install mongodb-org

mongo shell ( )

gt dbworldinsert( speech Hello World ) gt cur = dbworldfind()x=curnext()print(x[speech])

test world key value bull cur javascript next() x js bull

SQL MongoDB

(mongodb _id )

MongoDB JavaScript

mongo localhost27017mydb myjsfilejs

httpsriptutorialcomkohome 5

myjsfilejs A mongo mydb mongod localhost 27017 localhost27017 mongodb

mongo js

gtload(myjsfilejs)

gt dbtestinsert(keyvalue1key2Val2key3val3) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue2key2Val21key3val31) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue3key2Val22key3val33) WriteResult( nInserted 1 )

gt dbtestfind() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val2 1 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val2 2 key3 val33

pretty ()

gt dbtestfind()pretty() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val21 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val22 key3 val33 gt

show dbs

( mydb mydb

httpsriptutorialcomkohome 6

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 5: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

- AND OR IN 38

find () 41

Find () 41

find () 41

17 44

Examples 44

44

44

18 45

Examples 45

3 45

19 47

Examples 47

Mongodb 47

20 49

Examples 49

MongoDB Replica Set 49

21 51

51

51

Examples 51

51

51

51

51

51

53

53

54

54

54

22 56

Examples 56

56

23 57

57

57

57

Examples 57

$ set 57

I 57

57

III $ 58

24 60

Examples 60

60

60

60

25 62

62

62

62

62

Examples 62

62

63

64

64

64

( ) 65

26 67

67

Examples 67

67

68

27 69

69

69

Examples 69

pymongo MongoDB 69

PyMongo 69

PyMongo 70

71

You can share this PDF with anyone you feel could benefit from it downloaded the latest version from mongodb

It is an unofficial and free MongoDB ebook created for educational purposes All the content is extracted from Stack Overflow Documentation which is written by many hardworking individuals at Stack Overflow It is neither affiliated with Stack Overflow nor official MongoDB

The content is released under Creative Commons BY-SA and the list of contributors to each chapter are provided in the credits section at the end of this book Images may be copyright of their respective owners unless otherwise specified All trademarks and registered trademarks are the property of their respective company owners

Use the content presented in this book at your own risk it is not guaranteed to be correct nor accurate please send your feedback and corrections to infozzzprojectscom

httpsriptutorialcomkohome 1

1 MongoDB SQL NoSQL bullMongoDB NoSQL JSON JSON MongoDB bullMongoDB - mongod mongo bullv32 MongoDB Mongo javascript $ lookup javascript bullOperations Checklist bull

34 2016-11-29

32 2015-12-08

30 2015-03-03

26 2014-04-08

24 2013-03-19

22 2012-08-29

20 2011-09-12

18 2011-03-16

16 2010-08-31

14 2010-03-25

12 2009-12-10

Examples

MongoDB

Mac OS

Mac OS (homebrew)

homebrew

$ brew install mongodb

32 64 tgz

bull

httpsriptutorialcomkohome 2

$ tar xvf mongodb-osx-xyztgz

xyz tgz bin mongod mongo

datadb

$ sudo bash mkdir -p datadb chmod 777 data chmod 777 datadb exit

$ mongod

27017

$ mongo

test connecting to test connecting to test MongoDB Hello World

Windows

32 64

exe

mongodb CProgram FilesMongoDBServer32bin 32

bin mongod mongo

bull

httpsriptutorialcomkohome 3

Windows 10 Windows 10

db data

cmd Shift Ctrl GUI

gt mongod

27017

gt mongo

test connecting to test connecting to test MongoDB Hello World

Linux Mac OS

( apt-get )

MongoDB

$ sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv EA312927 gpg Total number processed 1 gpg imported 1 (RSA 1)

1604

$ echo deb httprepomongodborgaptubuntu xenialmongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

1404

$ echo deb httprepomongodborgaptubuntu trustymongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

$ sudo apt-get update

MongoDB

$ sudo apt-get install mongodb-org

Red Hat ( yum )

bull

httpsriptutorialcomkohome 4

$ vi etcyumreposdmongodb-org-34repo

[mongodb-org-34] name=MongoDB Repository baseurl=httpsrepomongodborgyumredhat$releasevermongodb-org34x86_64 gpgcheck=1 enabled=1 gpgkey=httpswwwmongodborgstaticpgpserver-34asc

$ sudo yum update

MongoDB

$ sudo yum install mongodb-org

mongo shell ( )

gt dbworldinsert( speech Hello World ) gt cur = dbworldfind()x=curnext()print(x[speech])

test world key value bull cur javascript next() x js bull

SQL MongoDB

(mongodb _id )

MongoDB JavaScript

mongo localhost27017mydb myjsfilejs

httpsriptutorialcomkohome 5

myjsfilejs A mongo mydb mongod localhost 27017 localhost27017 mongodb

mongo js

gtload(myjsfilejs)

gt dbtestinsert(keyvalue1key2Val2key3val3) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue2key2Val21key3val31) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue3key2Val22key3val33) WriteResult( nInserted 1 )

gt dbtestfind() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val2 1 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val2 2 key3 val33

pretty ()

gt dbtestfind()pretty() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val21 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val22 key3 val33 gt

show dbs

( mydb mydb

httpsriptutorialcomkohome 6

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 6: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

Examples 56

56

23 57

57

57

57

Examples 57

$ set 57

I 57

57

III $ 58

24 60

Examples 60

60

60

60

25 62

62

62

62

62

Examples 62

62

63

64

64

64

( ) 65

26 67

67

Examples 67

67

68

27 69

69

69

Examples 69

pymongo MongoDB 69

PyMongo 69

PyMongo 70

71

You can share this PDF with anyone you feel could benefit from it downloaded the latest version from mongodb

It is an unofficial and free MongoDB ebook created for educational purposes All the content is extracted from Stack Overflow Documentation which is written by many hardworking individuals at Stack Overflow It is neither affiliated with Stack Overflow nor official MongoDB

The content is released under Creative Commons BY-SA and the list of contributors to each chapter are provided in the credits section at the end of this book Images may be copyright of their respective owners unless otherwise specified All trademarks and registered trademarks are the property of their respective company owners

Use the content presented in this book at your own risk it is not guaranteed to be correct nor accurate please send your feedback and corrections to infozzzprojectscom

httpsriptutorialcomkohome 1

1 MongoDB SQL NoSQL bullMongoDB NoSQL JSON JSON MongoDB bullMongoDB - mongod mongo bullv32 MongoDB Mongo javascript $ lookup javascript bullOperations Checklist bull

34 2016-11-29

32 2015-12-08

30 2015-03-03

26 2014-04-08

24 2013-03-19

22 2012-08-29

20 2011-09-12

18 2011-03-16

16 2010-08-31

14 2010-03-25

12 2009-12-10

Examples

MongoDB

Mac OS

Mac OS (homebrew)

homebrew

$ brew install mongodb

32 64 tgz

bull

httpsriptutorialcomkohome 2

$ tar xvf mongodb-osx-xyztgz

xyz tgz bin mongod mongo

datadb

$ sudo bash mkdir -p datadb chmod 777 data chmod 777 datadb exit

$ mongod

27017

$ mongo

test connecting to test connecting to test MongoDB Hello World

Windows

32 64

exe

mongodb CProgram FilesMongoDBServer32bin 32

bin mongod mongo

bull

httpsriptutorialcomkohome 3

Windows 10 Windows 10

db data

cmd Shift Ctrl GUI

gt mongod

27017

gt mongo

test connecting to test connecting to test MongoDB Hello World

Linux Mac OS

( apt-get )

MongoDB

$ sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv EA312927 gpg Total number processed 1 gpg imported 1 (RSA 1)

1604

$ echo deb httprepomongodborgaptubuntu xenialmongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

1404

$ echo deb httprepomongodborgaptubuntu trustymongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

$ sudo apt-get update

MongoDB

$ sudo apt-get install mongodb-org

Red Hat ( yum )

bull

httpsriptutorialcomkohome 4

$ vi etcyumreposdmongodb-org-34repo

[mongodb-org-34] name=MongoDB Repository baseurl=httpsrepomongodborgyumredhat$releasevermongodb-org34x86_64 gpgcheck=1 enabled=1 gpgkey=httpswwwmongodborgstaticpgpserver-34asc

$ sudo yum update

MongoDB

$ sudo yum install mongodb-org

mongo shell ( )

gt dbworldinsert( speech Hello World ) gt cur = dbworldfind()x=curnext()print(x[speech])

test world key value bull cur javascript next() x js bull

SQL MongoDB

(mongodb _id )

MongoDB JavaScript

mongo localhost27017mydb myjsfilejs

httpsriptutorialcomkohome 5

myjsfilejs A mongo mydb mongod localhost 27017 localhost27017 mongodb

mongo js

gtload(myjsfilejs)

gt dbtestinsert(keyvalue1key2Val2key3val3) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue2key2Val21key3val31) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue3key2Val22key3val33) WriteResult( nInserted 1 )

gt dbtestfind() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val2 1 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val2 2 key3 val33

pretty ()

gt dbtestfind()pretty() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val21 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val22 key3 val33 gt

show dbs

( mydb mydb

httpsriptutorialcomkohome 6

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 7: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

67

68

27 69

69

69

Examples 69

pymongo MongoDB 69

PyMongo 69

PyMongo 70

71

You can share this PDF with anyone you feel could benefit from it downloaded the latest version from mongodb

It is an unofficial and free MongoDB ebook created for educational purposes All the content is extracted from Stack Overflow Documentation which is written by many hardworking individuals at Stack Overflow It is neither affiliated with Stack Overflow nor official MongoDB

The content is released under Creative Commons BY-SA and the list of contributors to each chapter are provided in the credits section at the end of this book Images may be copyright of their respective owners unless otherwise specified All trademarks and registered trademarks are the property of their respective company owners

Use the content presented in this book at your own risk it is not guaranteed to be correct nor accurate please send your feedback and corrections to infozzzprojectscom

httpsriptutorialcomkohome 1

1 MongoDB SQL NoSQL bullMongoDB NoSQL JSON JSON MongoDB bullMongoDB - mongod mongo bullv32 MongoDB Mongo javascript $ lookup javascript bullOperations Checklist bull

34 2016-11-29

32 2015-12-08

30 2015-03-03

26 2014-04-08

24 2013-03-19

22 2012-08-29

20 2011-09-12

18 2011-03-16

16 2010-08-31

14 2010-03-25

12 2009-12-10

Examples

MongoDB

Mac OS

Mac OS (homebrew)

homebrew

$ brew install mongodb

32 64 tgz

bull

httpsriptutorialcomkohome 2

$ tar xvf mongodb-osx-xyztgz

xyz tgz bin mongod mongo

datadb

$ sudo bash mkdir -p datadb chmod 777 data chmod 777 datadb exit

$ mongod

27017

$ mongo

test connecting to test connecting to test MongoDB Hello World

Windows

32 64

exe

mongodb CProgram FilesMongoDBServer32bin 32

bin mongod mongo

bull

httpsriptutorialcomkohome 3

Windows 10 Windows 10

db data

cmd Shift Ctrl GUI

gt mongod

27017

gt mongo

test connecting to test connecting to test MongoDB Hello World

Linux Mac OS

( apt-get )

MongoDB

$ sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv EA312927 gpg Total number processed 1 gpg imported 1 (RSA 1)

1604

$ echo deb httprepomongodborgaptubuntu xenialmongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

1404

$ echo deb httprepomongodborgaptubuntu trustymongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

$ sudo apt-get update

MongoDB

$ sudo apt-get install mongodb-org

Red Hat ( yum )

bull

httpsriptutorialcomkohome 4

$ vi etcyumreposdmongodb-org-34repo

[mongodb-org-34] name=MongoDB Repository baseurl=httpsrepomongodborgyumredhat$releasevermongodb-org34x86_64 gpgcheck=1 enabled=1 gpgkey=httpswwwmongodborgstaticpgpserver-34asc

$ sudo yum update

MongoDB

$ sudo yum install mongodb-org

mongo shell ( )

gt dbworldinsert( speech Hello World ) gt cur = dbworldfind()x=curnext()print(x[speech])

test world key value bull cur javascript next() x js bull

SQL MongoDB

(mongodb _id )

MongoDB JavaScript

mongo localhost27017mydb myjsfilejs

httpsriptutorialcomkohome 5

myjsfilejs A mongo mydb mongod localhost 27017 localhost27017 mongodb

mongo js

gtload(myjsfilejs)

gt dbtestinsert(keyvalue1key2Val2key3val3) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue2key2Val21key3val31) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue3key2Val22key3val33) WriteResult( nInserted 1 )

gt dbtestfind() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val2 1 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val2 2 key3 val33

pretty ()

gt dbtestfind()pretty() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val21 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val22 key3 val33 gt

show dbs

( mydb mydb

httpsriptutorialcomkohome 6

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 8: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

You can share this PDF with anyone you feel could benefit from it downloaded the latest version from mongodb

It is an unofficial and free MongoDB ebook created for educational purposes All the content is extracted from Stack Overflow Documentation which is written by many hardworking individuals at Stack Overflow It is neither affiliated with Stack Overflow nor official MongoDB

The content is released under Creative Commons BY-SA and the list of contributors to each chapter are provided in the credits section at the end of this book Images may be copyright of their respective owners unless otherwise specified All trademarks and registered trademarks are the property of their respective company owners

Use the content presented in this book at your own risk it is not guaranteed to be correct nor accurate please send your feedback and corrections to infozzzprojectscom

httpsriptutorialcomkohome 1

1 MongoDB SQL NoSQL bullMongoDB NoSQL JSON JSON MongoDB bullMongoDB - mongod mongo bullv32 MongoDB Mongo javascript $ lookup javascript bullOperations Checklist bull

34 2016-11-29

32 2015-12-08

30 2015-03-03

26 2014-04-08

24 2013-03-19

22 2012-08-29

20 2011-09-12

18 2011-03-16

16 2010-08-31

14 2010-03-25

12 2009-12-10

Examples

MongoDB

Mac OS

Mac OS (homebrew)

homebrew

$ brew install mongodb

32 64 tgz

bull

httpsriptutorialcomkohome 2

$ tar xvf mongodb-osx-xyztgz

xyz tgz bin mongod mongo

datadb

$ sudo bash mkdir -p datadb chmod 777 data chmod 777 datadb exit

$ mongod

27017

$ mongo

test connecting to test connecting to test MongoDB Hello World

Windows

32 64

exe

mongodb CProgram FilesMongoDBServer32bin 32

bin mongod mongo

bull

httpsriptutorialcomkohome 3

Windows 10 Windows 10

db data

cmd Shift Ctrl GUI

gt mongod

27017

gt mongo

test connecting to test connecting to test MongoDB Hello World

Linux Mac OS

( apt-get )

MongoDB

$ sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv EA312927 gpg Total number processed 1 gpg imported 1 (RSA 1)

1604

$ echo deb httprepomongodborgaptubuntu xenialmongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

1404

$ echo deb httprepomongodborgaptubuntu trustymongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

$ sudo apt-get update

MongoDB

$ sudo apt-get install mongodb-org

Red Hat ( yum )

bull

httpsriptutorialcomkohome 4

$ vi etcyumreposdmongodb-org-34repo

[mongodb-org-34] name=MongoDB Repository baseurl=httpsrepomongodborgyumredhat$releasevermongodb-org34x86_64 gpgcheck=1 enabled=1 gpgkey=httpswwwmongodborgstaticpgpserver-34asc

$ sudo yum update

MongoDB

$ sudo yum install mongodb-org

mongo shell ( )

gt dbworldinsert( speech Hello World ) gt cur = dbworldfind()x=curnext()print(x[speech])

test world key value bull cur javascript next() x js bull

SQL MongoDB

(mongodb _id )

MongoDB JavaScript

mongo localhost27017mydb myjsfilejs

httpsriptutorialcomkohome 5

myjsfilejs A mongo mydb mongod localhost 27017 localhost27017 mongodb

mongo js

gtload(myjsfilejs)

gt dbtestinsert(keyvalue1key2Val2key3val3) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue2key2Val21key3val31) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue3key2Val22key3val33) WriteResult( nInserted 1 )

gt dbtestfind() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val2 1 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val2 2 key3 val33

pretty ()

gt dbtestfind()pretty() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val21 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val22 key3 val33 gt

show dbs

( mydb mydb

httpsriptutorialcomkohome 6

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 9: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

1 MongoDB SQL NoSQL bullMongoDB NoSQL JSON JSON MongoDB bullMongoDB - mongod mongo bullv32 MongoDB Mongo javascript $ lookup javascript bullOperations Checklist bull

34 2016-11-29

32 2015-12-08

30 2015-03-03

26 2014-04-08

24 2013-03-19

22 2012-08-29

20 2011-09-12

18 2011-03-16

16 2010-08-31

14 2010-03-25

12 2009-12-10

Examples

MongoDB

Mac OS

Mac OS (homebrew)

homebrew

$ brew install mongodb

32 64 tgz

bull

httpsriptutorialcomkohome 2

$ tar xvf mongodb-osx-xyztgz

xyz tgz bin mongod mongo

datadb

$ sudo bash mkdir -p datadb chmod 777 data chmod 777 datadb exit

$ mongod

27017

$ mongo

test connecting to test connecting to test MongoDB Hello World

Windows

32 64

exe

mongodb CProgram FilesMongoDBServer32bin 32

bin mongod mongo

bull

httpsriptutorialcomkohome 3

Windows 10 Windows 10

db data

cmd Shift Ctrl GUI

gt mongod

27017

gt mongo

test connecting to test connecting to test MongoDB Hello World

Linux Mac OS

( apt-get )

MongoDB

$ sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv EA312927 gpg Total number processed 1 gpg imported 1 (RSA 1)

1604

$ echo deb httprepomongodborgaptubuntu xenialmongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

1404

$ echo deb httprepomongodborgaptubuntu trustymongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

$ sudo apt-get update

MongoDB

$ sudo apt-get install mongodb-org

Red Hat ( yum )

bull

httpsriptutorialcomkohome 4

$ vi etcyumreposdmongodb-org-34repo

[mongodb-org-34] name=MongoDB Repository baseurl=httpsrepomongodborgyumredhat$releasevermongodb-org34x86_64 gpgcheck=1 enabled=1 gpgkey=httpswwwmongodborgstaticpgpserver-34asc

$ sudo yum update

MongoDB

$ sudo yum install mongodb-org

mongo shell ( )

gt dbworldinsert( speech Hello World ) gt cur = dbworldfind()x=curnext()print(x[speech])

test world key value bull cur javascript next() x js bull

SQL MongoDB

(mongodb _id )

MongoDB JavaScript

mongo localhost27017mydb myjsfilejs

httpsriptutorialcomkohome 5

myjsfilejs A mongo mydb mongod localhost 27017 localhost27017 mongodb

mongo js

gtload(myjsfilejs)

gt dbtestinsert(keyvalue1key2Val2key3val3) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue2key2Val21key3val31) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue3key2Val22key3val33) WriteResult( nInserted 1 )

gt dbtestfind() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val2 1 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val2 2 key3 val33

pretty ()

gt dbtestfind()pretty() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val21 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val22 key3 val33 gt

show dbs

( mydb mydb

httpsriptutorialcomkohome 6

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 10: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

$ tar xvf mongodb-osx-xyztgz

xyz tgz bin mongod mongo

datadb

$ sudo bash mkdir -p datadb chmod 777 data chmod 777 datadb exit

$ mongod

27017

$ mongo

test connecting to test connecting to test MongoDB Hello World

Windows

32 64

exe

mongodb CProgram FilesMongoDBServer32bin 32

bin mongod mongo

bull

httpsriptutorialcomkohome 3

Windows 10 Windows 10

db data

cmd Shift Ctrl GUI

gt mongod

27017

gt mongo

test connecting to test connecting to test MongoDB Hello World

Linux Mac OS

( apt-get )

MongoDB

$ sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv EA312927 gpg Total number processed 1 gpg imported 1 (RSA 1)

1604

$ echo deb httprepomongodborgaptubuntu xenialmongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

1404

$ echo deb httprepomongodborgaptubuntu trustymongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

$ sudo apt-get update

MongoDB

$ sudo apt-get install mongodb-org

Red Hat ( yum )

bull

httpsriptutorialcomkohome 4

$ vi etcyumreposdmongodb-org-34repo

[mongodb-org-34] name=MongoDB Repository baseurl=httpsrepomongodborgyumredhat$releasevermongodb-org34x86_64 gpgcheck=1 enabled=1 gpgkey=httpswwwmongodborgstaticpgpserver-34asc

$ sudo yum update

MongoDB

$ sudo yum install mongodb-org

mongo shell ( )

gt dbworldinsert( speech Hello World ) gt cur = dbworldfind()x=curnext()print(x[speech])

test world key value bull cur javascript next() x js bull

SQL MongoDB

(mongodb _id )

MongoDB JavaScript

mongo localhost27017mydb myjsfilejs

httpsriptutorialcomkohome 5

myjsfilejs A mongo mydb mongod localhost 27017 localhost27017 mongodb

mongo js

gtload(myjsfilejs)

gt dbtestinsert(keyvalue1key2Val2key3val3) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue2key2Val21key3val31) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue3key2Val22key3val33) WriteResult( nInserted 1 )

gt dbtestfind() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val2 1 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val2 2 key3 val33

pretty ()

gt dbtestfind()pretty() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val21 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val22 key3 val33 gt

show dbs

( mydb mydb

httpsriptutorialcomkohome 6

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 11: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

Windows 10 Windows 10

db data

cmd Shift Ctrl GUI

gt mongod

27017

gt mongo

test connecting to test connecting to test MongoDB Hello World

Linux Mac OS

( apt-get )

MongoDB

$ sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv EA312927 gpg Total number processed 1 gpg imported 1 (RSA 1)

1604

$ echo deb httprepomongodborgaptubuntu xenialmongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

1404

$ echo deb httprepomongodborgaptubuntu trustymongodb-org32 multiverse | sudo tee etcaptsourceslistdmongodb-org-32list

$ sudo apt-get update

MongoDB

$ sudo apt-get install mongodb-org

Red Hat ( yum )

bull

httpsriptutorialcomkohome 4

$ vi etcyumreposdmongodb-org-34repo

[mongodb-org-34] name=MongoDB Repository baseurl=httpsrepomongodborgyumredhat$releasevermongodb-org34x86_64 gpgcheck=1 enabled=1 gpgkey=httpswwwmongodborgstaticpgpserver-34asc

$ sudo yum update

MongoDB

$ sudo yum install mongodb-org

mongo shell ( )

gt dbworldinsert( speech Hello World ) gt cur = dbworldfind()x=curnext()print(x[speech])

test world key value bull cur javascript next() x js bull

SQL MongoDB

(mongodb _id )

MongoDB JavaScript

mongo localhost27017mydb myjsfilejs

httpsriptutorialcomkohome 5

myjsfilejs A mongo mydb mongod localhost 27017 localhost27017 mongodb

mongo js

gtload(myjsfilejs)

gt dbtestinsert(keyvalue1key2Val2key3val3) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue2key2Val21key3val31) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue3key2Val22key3val33) WriteResult( nInserted 1 )

gt dbtestfind() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val2 1 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val2 2 key3 val33

pretty ()

gt dbtestfind()pretty() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val21 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val22 key3 val33 gt

show dbs

( mydb mydb

httpsriptutorialcomkohome 6

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 12: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

$ vi etcyumreposdmongodb-org-34repo

[mongodb-org-34] name=MongoDB Repository baseurl=httpsrepomongodborgyumredhat$releasevermongodb-org34x86_64 gpgcheck=1 enabled=1 gpgkey=httpswwwmongodborgstaticpgpserver-34asc

$ sudo yum update

MongoDB

$ sudo yum install mongodb-org

mongo shell ( )

gt dbworldinsert( speech Hello World ) gt cur = dbworldfind()x=curnext()print(x[speech])

test world key value bull cur javascript next() x js bull

SQL MongoDB

(mongodb _id )

MongoDB JavaScript

mongo localhost27017mydb myjsfilejs

httpsriptutorialcomkohome 5

myjsfilejs A mongo mydb mongod localhost 27017 localhost27017 mongodb

mongo js

gtload(myjsfilejs)

gt dbtestinsert(keyvalue1key2Val2key3val3) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue2key2Val21key3val31) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue3key2Val22key3val33) WriteResult( nInserted 1 )

gt dbtestfind() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val2 1 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val2 2 key3 val33

pretty ()

gt dbtestfind()pretty() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val21 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val22 key3 val33 gt

show dbs

( mydb mydb

httpsriptutorialcomkohome 6

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 13: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

myjsfilejs A mongo mydb mongod localhost 27017 localhost27017 mongodb

mongo js

gtload(myjsfilejs)

gt dbtestinsert(keyvalue1key2Val2key3val3) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue2key2Val21key3val31) WriteResult( nInserted 1 ) gt dbtestinsert(keyvalue3key2Val22key3val33) WriteResult( nInserted 1 )

gt dbtestfind() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val2 1 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val2 2 key3 val33

pretty ()

gt dbtestfind()pretty() _id ObjectId(5790c5cecae25b3d38c3c7ae) key value1 key2 Val2 key3 val3 _id ObjectId(5790c5d9cae25b3d38c3c7af) key value2 key2 Val21 key3 val31 _id ObjectId(5790c5e9cae25b3d38c3c7b0) key value3 key2 Val22 key3 val33 gt

show dbs

( mydb mydb

httpsriptutorialcomkohome 6

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 14: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

use mydb

( )

show collections

dbmydbhelp()

db

gt db mydb

dbdropDatabase()

dbdropDatabase()

MongoDB httpsriptutorialcomkomongodbtopic691mongodb-

httpsriptutorialcomkohome 7

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 15: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

2 2dsphere

Examples

2dsphere

dbcollectioncreateIndex() 2dsphere 2dsphere

dbcollectioncreateIndex( ltlocation fieldgt 2dsphere )

location field 2dsphere places 2dsphre

dbplacesinsert( loc type Point coordinates [ -7397 4077 ] name Central Park category Parks )

places loc 2dsphere

dbplacescreateIndex( loc 2dsphere )

2dsphere httpsriptutorialcomkomongodbtopic66322dsphere-

httpsriptutorialcomkohome 8

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 16: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

3 CRUD ( )bullinsertOne ( writeConcern )bullinsertMany ([ 1 2 ] writeConcern )bull( )bullfindOne ( )bull( )bullupdateOne ( upsert writeConcern )bullupdateMany ( upsert writeConcern )bullreplaceOne ( upsert writeConcern )bullremove ( query justOne )bullfindAndModify ( [ ] )bull

Examples

dbpeopleinsert(name Tom age 28)

dbpeoplesave(name Tom age 28)

save _id _id

MongoDB 32x -

insertOne

dbpeopleinsertOne(name Tom age 28)

insertMany

dbpeopleinsertMany([name Tom age 28name John age 25 name Kathy age 23])

insert 30 CRUD

dbpeopleupdate(name Tom age 29 name Tom) New in MongoDB 32 dbpeopleupdateOne(name Tomage 29 name Tom) Will replace only first matching document dbpeopleupdateMany(name Tomage 29 name Tom) Will replace all matching documents

httpsriptutorialcomkohome 9

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 17: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

age

dbpeopleupdate(name Tom $set age 29)

Tom

dbpeopleupdate(name Tom $set age 29 multi true) New in MongoDB 32 dbpeopleupdateOne(name Tom$setage 30) Will update only first matching document dbpeopleupdateMany(name Tom$setage 30) Will update all matching documents

dbpeopleupdateMany(name Tom$setage 30 salary50000) Document will have `salary` field as well

dbcollectionreplaceOne(nameTom nameLakmalage25addressSri Lanka)

New in MongoDB 32 dbpeopledeleteMany(name Tom) All versions dbpeopleremove(name Tom)

New in MongoDB 32 dbpeopledeleteOne(name Tom) All versions dbpeopleremove(name Tom true)

MongoDB remove()

dbpeopleremove()

dbpeopleremove()

name Tom people

dbpeoplefind(name Tom)

httpsriptutorialcomkohome 10

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 18: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

dbpeoplefindOne(name Tom)

_id age

dbpeoplefind(name Tom _id 0 age 1)

_id _id 0 ( _id false ) _id _id 0 _id country

dbpeoplefind(addresscountry US)

(amp I)

dbpeoplefind(addresscountry US name true addresscity true)Remember that the result has a `pretty()` method that pretty-prints resulting JSON dbpeoplefind()pretty()

$set $push nicknames

dbpeopleupdate(name Tom $push nicknames Tommy) This adds the string Tommy into the nicknames array in Toms document

$pull $push

dbpeopleupdate(name Tom $pull nicknames Tommy) This removes the string Tommy from the nicknames array in Toms document

$pop Tom [Marie Bob Kevin Alex]

dbpeopleupdate(name Tom $pop siblings -1) This will remove the first value from the siblings array which is Marie in this case dbpeopleupdate(name Tom $pop siblings 1) This will remove the last value from the siblings array which is Alex in this case

multi

multi true

dbcollectionupdate( query update upsert boolean multi boolean writeConcern document

httpsriptutorialcomkohome 11

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 19: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

)

true false false

MongoDB _id ObjectId (59835487adf45ec6) title NoSQL _id dbid = ObjectId (59835487adf45ec7) title

dbmycolupdate ( title MongoDB $ set title MongoDB Tutorial multi true)

name Tom age 28 marks [50 60 70]

Tom 55 50 ( $ )

dbpeopleupdate(name Tom marks 50 $set marks$ 55)

name Tom age 28 marks [subject English marks 90subject Maths marks 100 subject Computes marks 20]

Tom 85

dbpeopleupdate(name Tom markssubject English$setmarks$marks 85)

name Tom markssubject English marks subject marks $ marks $ marks

$

_id 1 grades [ 80 85 90 ] _id 2 grades [ 88 90 92 ] _id 3 grades [ 85 100 90 ]

80 82 $

dbstudentsupdate( _id 1 grades 80 $set grades$ 82 )

CRUD httpsriptutorialcomkomongodbtopic1683crud-

httpsriptutorialcomkohome 12

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 20: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

4 MongoDB - TLS SSL ReplicaSet TLS SSL ReplicaSet

3 PRODUCTION

ReplicaSet

Mongo Shell

TLS SSL PKI ( )

Examples

TLS SSL ReplicaSet

(CA File )

openssl req -nodes -out capem -new -x509 -keyout cakey

(CSR ) ( CN) ( IP) etc hosts

CSR RSA (4096 )

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_1key -out mongodb_node_1csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_2key -out mongodb_node_2csr openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_node_3key -out mongodb_node_3csr

ReplicaSet CSR CSR

3 CSR 3

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr

CA (capem) (cakey)

openssl x509 -req -in mongodb_node_1csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_1crt openssl x509 -req -in mongodb_node_2csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_2crt openssl x509 -req -in mongodb_node_3csr -CA capem -CAkey cakey -set_serial 00 -out mongodb_node_3crt

httpsriptutorialcomkohome 13

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 21: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

CSR

3 CSR 3 3 MongoDB

mongodb_node_1key - mongodb_node_2key - mongodb_node_3key mongodb_node_1csr - mongodb_node_2csr - mongodb_node_3csr mongodb_node_1crt - mongodb_node_2crt - mongodb_node_3crt

CSR CN

(MongoDB )

cat mongodb_node_1key mongodb_node_1crt gt mongodb_node_1pem cat mongodb_node_2key mongodb_node_2crt gt mongodb_node_2pem cat mongodb_node_3key mongodb_node_3crt gt mongodb_node_3pem

PEM 3

mongodb_node_1pem - mongodb_node_2pem - mongodb_node_3pem

ReplicaSet

pem data data1 data data2 data data3

27017 27018 27019 3 ReplicaSet

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem

3 ReplicaSet TLS ReplicaSet

SSL ReplicaSet

( SSL) CA

mongod --dbpath datadata_1 --replSet rs0 --port 27017 --sslMode requireSSL --sslPEMKeyFile mongodb_node_1pem --sslCAFile capem mongod --dbpath datadata_2 --replSet rs0 --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb_node_2pem --sslCAFile capem mongod --dbpath datadata_3 --replSet rs0 --port 27019 --sslMode requireSSL --sslPEMKeyFile mongodb_node_3pem --sslCAFile capem

httpsriptutorialcomkohome 14

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 22: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

3 ReplicaSet TLS CA ReplicaSet

(Mongo Shell) ReplicaSet

SSL

TLS SSL ReplicaSet CA (capem) CA

3 mongo1 27017 mongo2 27018 mongo3 27019 ( etc hosts )

MongoDB 326 CA CA ReplicaSet

mongo --ssl --host rs0mongo127017mongo227018mongo327019

CA

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019

ReplicaSet Mongo Shell ReplicaSet

SSL

ReplicaSet ReplicaSet CA

CSR Common Name Field 1 ReplicaSet

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr Common Name (eg server FQDN or YOUR name) [] mongo1mongo2mongo3

(64 ) CSR SubjectAltName

openssl req -nodes -newkey rsa4096 -sha256 -keyout mongodb_clientkey -out mongodb_clientcsr -config lt( cat ltlt-EOF [req] default_bits = 4096 prompt = no default_md = sha256 req_extensions = req_ext distinguished_name = dn [ dn ] CN = [ req_ext ] subjectAltName = alt_names [ alt_names ] DNS1 = mongo1 DNS2 = mongo2

httpsriptutorialcomkohome 15

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 23: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

DNS3 = mongo3 EOF )

CA CSR

openssl x509 -req -in mongodb_clientcsr -CA capem -CAkey cakey -set_serial 00 -out mongodb_clientcrt

cat mongodb_clientkey mongodb_clientcrt gt mongodb_clientpem

ReplicaSet

mongo --ssl --sslCAFile capem --host rs0mongo127017mongo227018mongo327019 --sslPEMKeyFile mongodb_clientpem

ReplicaSet Mongo Shell ReplicaSet

MongoDB - TLS SSL ReplicaSet httpsriptutorialcomkomongodbtopic9539mongodb---tls---ssl--replicaset-

httpsriptutorialcomkohome 16

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 24: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

5 MongoDB

Examples

dbcurrentOp()

inprog [ opid 302616759 active true secs_running 1 microsecs_running NumberLong(1167662) op getmore ns localoplogrs query desc conn48 threadId 0x114c00700 connectionId 48 opid mdss_shard00302616760 active true secs_running 1 microsecs_running NumberLong(1169659) op getmore ns localoplogrs ]

inprog opid ID secs_running

MongoDB httpsriptutorialcomkomongodbtopic7553mongodb-

httpsriptutorialcomkohome 17

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 25: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

6 MongoDB MongoDB

MongoDB 30 34 30 -gt 32 -gt 34

Examples

apt 1604 34

34 32 apt

sudo service mongod stop0 sudo apt-key adv --keyserver hkpkeyserverubuntucom80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

1

echo deb [ arch=amd64arm64 ] httprepomongodborgaptubuntu xenialmongodb-org34 multiverse | sudo tee etcaptsourceslistdmongodb-org-34list

2

sudo apt-get update3 sudo apt-get upgrade4 sudo service mongod start5

mongo MongoDB 34

MongoDB httpsriptutorialcomkomongodbtopic9851mongodb--

httpsriptutorialcomkohome 18

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 26: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

7 MongoDB MongoDB 1 ltbrgt ()

Examples

read1 readwrite2

MongoDB httpsriptutorialcomkomongodbtopic8114mongodb--

httpsriptutorialcomkohome 19

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 27: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

8 MongoDB

Examples

mongo

dbemployeesinsert(nameAdmadeptAdminlanguages[germanfrenchenglishhindi]age30totalExp10) dbemployeesinsert(nameAnnadeptAdminlanguages[englishhindi]age35 totalExp11) dbemployeesinsert(nameBobdeptFacilitieslanguages[englishhindi]age36totalExp14) dbemployeesinsert(nameCathydeptFacilitieslanguages[hindi]age31 totalExp4) dbemployeesinsert(nameMikedeptHRlanguages[english hindi spanish]age26 totalExp3) dbemployeesinsert(nameJennydeptHRlanguages[english hindi spanish]age25 totalExp3)

1 (SQL where )

dbemployeesaggregate([$matchdeptAdmin]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin languages [ german french english hindi ] age 30 totalExp 10 _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin languages [ english hindi ] age 35 totalExp 11

2

_id

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept Admin _id ObjectId(54982fc92e9b4b54ec384a0e) name Anna dept Admin dbemployeesaggregate($project _id0 name 1) Output name Adma name Anna name Bob name Cathy name Mike name Jenny

3 $ null

httpsriptutorialcomkohome 20

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 28: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

dbemployeesaggregate([$group_id$dept]) _id HR _id Facilities _id Admin dbemployeesaggregate([$group_idnull totalAge$sum$age]) Output _id null noOfEmployee 183

4 $ sum

dbemployeesaggregate([$group_id$dept noOfDept$sum1]) Output _id HR noOfDept 2 _id Facilities noOfDept 2 _id Admin noOfDept 2

5

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 avgExp$avg$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 9 _id Admin noOfEmployee 2 totalExp 105

6

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 minExp$min$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 4 _id Admin noOfEmployee 2 totalExp 10

7

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp]) Output _id HR noOfEmployee 2 totalExp 3 _id Facilities noOfEmployee 2 totalExp 14 _id Admin noOfEmployee 2 totalExp 11

8 doucument

dbemployeesaggregate([$group_id$age lasts$last$name firsts$first$name]) Output _id 25 lasts Jenny firsts Jenny _id 26 lasts Mike firsts Mike

httpsriptutorialcomkohome 21

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 29: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

_id 35 lasts Cathy firsts Anna _id 30 lasts Adma firsts Adma

9 Minumum

dbemployeesaggregate([$group_id$dept noOfEmployee$sum1 maxExp$max$totalExp minExp$min $totalExp]) Output _id HR noOfEmployee 2 maxExp 3 minExp 3 _id Facilities noOfEmployee 2 maxExp 14 minExp 4 _id Admin noOfEmployee 2 maxExp 11 minExp 10

10 addToSet push addToSet

dbemployeesaggregate([$group_iddept arrPush$push$age arrSet $addToSet$age]) Output _id dept arrPush [ 30 35 35 35 26 25 ] arrSet [ 25 26 35 30 ]

11 Unwind

dbemployeesaggregate([$matchnameAdma $unwind$languages]) Output _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages german age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages french age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages english age 30 totalExp 10 _id ObjectId(54982fac2e9b4b54ec384a0d) name Adma dept HR languages hindi age 30 totalExp 10

12

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name 1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

13

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $skip1]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin

14

httpsriptutorialcomkohome 22

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 30: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 $sort name -1 $limit1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

15

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $gt [$age 30]]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

16

dbemployeesaggregate([$matchdeptAdmin age $gt30 $projectname1 dept1]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin

$ cmp $ eq $ gt $ gte $ lt $ lte $ ne

17

dbemployeesaggregate([$matchdeptAdmin $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e553dedf0228d4862ac) name Adma dept Admin age false _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

18

dbemployeesaggregate([$matchdeptAdmin $and [age $gt 30 age $lt 36 ] $projectname1 dept1 age $and [ $gt [ $age 30 ] $lt [ $age 36 ] ] ]) Output _id ObjectId(57ff3e5e3dedf0228d4862ad) name Anna dept Admin age true

$ and $ and $

httpsdocsmongodbcomv32referenceoperatoraggregation

Java Spring

MongoDB

httpsriptutorialcomkohome 23

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 31: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

try MongoClient mongo = new MongoClient() DB db = mongogetDB(so) DBCollection coll = dbgetCollection(employees) Equivalent to $match DBObject matchFields = new BasicDBObject() matchFieldsput(dept Admin) DBObject match = new BasicDBObject($match matchFields) Equivalent to $project DBObject projectFields = new BasicDBObject() projectFieldsput(_id 1) projectFieldsput(name 1) projectFieldsput(dept 1) projectFieldsput(totalExp 1) projectFieldsput(age 1) projectFieldsput(languages 1) DBObject project = new BasicDBObject($project projectFields) Equivalent to $group DBObject groupFields = new BasicDBObject(_id $dept) groupFieldsput(ageSet new BasicDBObject($addToSet $age)) DBObject employeeDocProjection = new BasicDBObject($addToSet new BasicDBObject(totalExp $totalExp)append(age $age)append(languages $languages)append(dept $dept)append(name $name)) groupFieldsput(docs employeeDocProjection) DBObject group = new BasicDBObject($group groupFields) Sort results by age DBObject sort = new BasicDBObject($sort new BasicDBObject(age 1)) ListltDBObjectgt aggregationList = new ArrayListltgt() aggregationListadd(match) aggregationListadd(project) aggregationListadd(group) aggregationListadd(sort) AggregationOutput output = collaggregate(aggregationList) for (DBObject result outputresults()) BasicDBList employeeList = (BasicDBList) resultget(docs) BasicDBObject employeeDoc = (BasicDBObject) employeeListget(0) String name = employeeDocget(name)toString() Systemoutprintln(name) catch (Exception ex) exprintStackTrace()

JSON resultSet

[ _id Admin ageSet [350 300] docs [ totalExp 110 age 350 languages [english hindi] dept Admin name Anna

httpsriptutorialcomkohome 24

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 32: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

totalExp 100 age 300 languages [german french english hindi] dept Admin name Adma ] ]

resultSet ageSet _id docs UI

$sample aggregation

dbemplyeesaggregate( $sample size1 )

size

($ Lookup)

let col_1 = dbcollection(col_1) let col_2 = dbcollection(col_2) col_1 aggregate([ $match _id 1 $lookup from col_2 localField id foreignField id as new_document ]function (err result) ressend(result) )

mongodb 32

Mongodb $ LookUp

MongoDB httpsriptutorialcomkomongodbtopic7417mongodb-

httpsriptutorialcomkohome 25

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 33: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

9 MongoDB ( ) MongoDB

MongoDB MongoDB

Examples

MongoDB

SCRAM-SHA-1bull

X509 bull

MongoDB (MONGODB-CR)bull

LDAP bull

Kerberos bull

bullX509bull

MongoDB httpsriptutorialcomkomongodbtopic8113mongodb--

httpsriptutorialcomkohome 26

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 34: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

10 Pluggable Storage EngineMongoDB 30 MMAP () WiredTiger MMAP WiredTiger

MMAP WiredTiger

MongoDB 32 WiredTiger

Examples

MMAP

MMAP mmap() Linux mmap() read()

MMAP WiredTiger MMAP

WiredTiger

WiredTiger LSM LSM

WiredTiger

WiredTiger

WiredTiger Snappy zLib Snappy CPU zLib

WiredTiger

mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt

mongodb 32 WiredTiger1 newWiredTigerDBPath newWiredTigerDBPath 2

mongodump --out ltexportDataDestinationgt mongod --storageEngine wiredTiger --dbpath ltnewWiredTigerDBPathgt mongorestore ltexportDataDestinationgt

Facebook RocksDB -

- io

SanDisk OS

httpsriptutorialcomkohome 27

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 35: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

TokuMX

Percona

Pluggable Storage Engine httpsriptutorialcomkomongodbtopic694pluggable-storage-engine

httpsriptutorialcomkohome 28

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 36: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

11 Upserts

Examples

_id 12 16 _id MongoDB ID 12 4 ID 3 mongodb ID 3

dbmycolinsert( _id ObjectId(7df78ad8902c) title MongoDB Overview description MongoDB is no sql database by tutorials point url httpwwwtutorialspointcom tags [mongodb database NoSQL] likes 100 )

mycol MongoDB _id MongoDB ObjectId

Upserts httpsriptutorialcomkomongodbtopic10185upserts--

httpsriptutorialcomkohome 29

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 37: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

12

systemLogverbosity 0

systemLogquiet

systemLogtraceAllExceptions

systemLogsyslogFacility

systemLogpath -

systemLoglogAppend

systemLoglogRotate

systemLogdestination

systemLogtimeStampFormat iso8601-

systemLogcomponentaccessControlverbosity 0

systemLogcomponentcommandverbosity 0

systemLogcomponentcontrolverbosity 0

systemLogcomponentftdcverbosity 0

systemLogcomponentgeoverbosity 0

systemLogcomponentindexverbosity 0

systemLogcomponentnetworkverbo 0

systemLogcomponentqueryverbosity 0

systemLogcomponentreplicationverbosity 0

systemLogcomponentshardingverbosity 0

systemLogcomponentstorageverbosity 0

systemLogcomponentstoragejournalverbosity 0

systemLogcomponentwriteverbosity 0

processManagementfork

processManagementpidFilePath

httpsriptutorialcomkohome 30

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 38: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

netport 27017

netbindIp 0000

netmaxIncomingConnections 65536

netwireObjectCheck

netipv6

netunixDomainSocketenabled

netunixDomainSocketpathPrefix tmp

netunixDomainSocketfilePermissions 0700

nethttpenabled

nethttpJSONPEnabled

nethttpRESTInterfaceEnabled

netsslsslOnNormalPorts

netsslmode

netsslPEMKeyFile

netsslPEMKeyPassword

netsslclusterFile

netsslclusterPassword

netsslCA

netsslCRLFile

netsslallowConnectionsWithoutCertificates

netsslallowInvalidCertificates

netsslallowInvalidHostnames

netssldisabledProtocols

netsslFIPSMode

Examples

httpsriptutorialcomkohome 31

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 39: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

mongo

--config

$ binmongod --config etcmongodconf $ binmongos --config etcmongosconf

-f --config

httpsriptutorialcomkomongodbtopic5985

httpsriptutorialcomkohome 32

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 40: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

13

Examples

name Alice salary 57871 dob 1986-08-21 name Bob salary 48974 dob 1990-11-04

name Alice salary 57871 dob ISODate(1986-08-21T000000000Z) name Bob salary 48974 dob ISODate(1990-11-04T000000000Z)

forEach() snapshot

dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) dbtestupdateOne( _id doc_id $set salary newSalary dob newDob ) )

Bulk() API forEach() 1000

forEach() MongoDB gt= 26 lt 32 Bulk() API initializeUnorderedBulkOp()

httpsriptutorialcomkohome 33

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 41: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

salary dob numerical datetime clients

var bulk = dbtestinitializeUnorderedBulkOp() counter = 0 counter to keep track of the batch update size dbtestfind( salary $exists true $type 2 dob $exists true $type 2 )snapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkfind( _id doc_id )updateOne( $set salary newSalary dob newDob ) counter++ increment counter if (counter 1000 == 0) bulkexecute() Execute per 1000 operations and re-initialize every 1000 update statements bulk = dbtestinitializeUnorderedBulkOp() )

MongoDB 32 Bulk() API bulkWrite() apis

forEach() 1000 1000 1000

var cursor = dbtestfind( salary $exists true $type 2 dob $exists true $type 2 ) bulkUpdateOps = [] cursorsnapshot()forEach(function(doc) var newSalary = parseInt(docsalary) newDob = new ISODate(docdob) bulkUpdateOpspush( updateOne filter _id doc_id update $set salary newSalary dob newDob ) if (bulkUpdateOpslength === 1000) dbtestbulkWrite(bulkUpdateOps) bulkUpdateOps = [] ) if (bulkUpdateOpslength gt 0) dbtestbulkWrite(bulkUpdateOps)

httpsriptutorialcomkomongodbtopic6211-

httpsriptutorialcomkohome 34

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 42: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

14

Examples

JSON mongoimport

c Users yc03ak1 Desktop zipsjson zipcodesjson

_id 01001 city AGAWAM loc [ -72622739 42070206 ] pop 15338 state MA _id 01002 city CUSHMAN loc [ -7251564999999999 42377017 ] pop 36963 state MA _id 01005 city BARRE loc [ -7210835400000001 42409698 ] pop 4546 state MA _id 01007 city BELCHERTOWN loc [ -7241095300000001 42275103 ] pop 10579 state MA _id 01008 city BLANDFORD loc [ -72936114 42182949 ] pop 1240 state MA _id 01010 city BRIMFIELD loc [ -72188455 42116543 ] pop 3706 state MA _id 01011 city CHESTER loc [ -72988761 42279421 ] pop 1688 state MA

test zips

CUsersyc03ak1gtmongoimport --db test --collection zips --drop --type json --host localhost47019 --file cUsersyc03ak1Desktopzipsjson

--db bull--collection bull--drop bull--type JSONbull--host mongodb bull--file json bull

2016-08-10T201050159-0700 connected to localhost47019 2016-08-10T201050163-0700 dropping testzips 2016-08-10T201053155-0700 [] testzips 21 MB30 MB (685) 2016-08-10T201056150-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057819-0700 [] testzips 30 MB30 MB (1000) 2016-08-10T201057821-0700 imported 29353 documents

CSV mongoimport

c Users yc03ak1 Desktop testingcsv CSV

_id city loc pop state

httpsriptutorialcomkohome 35

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 43: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

1 A [100 200] 2222 PQE 2 B [101 201] 22122 RW 3 C [102 200] 255222 RWE 4 D [103 203] 226622 SFDS 5 E [104 200] 222122 FDS

test sample

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --headerline --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--headerline csv json bull

2016-08-10T202548572-0700 connected to localhost47019 2016-08-10T202548576-0700 dropping testsample 2016-08-10T202549109-0700 imported 5 documents

CUsersyc03ak1gtmongoimport --db test --collection sample --drop --type csv --fields _idcitylocpopstate --host localhost47019 --file cUsersyc03ak1Desktoptestingcsv

--fields json bull

2016-08-10T202648978-0700 connected to localhost47019 2016-08-10T202648982-0700 dropping testsample 2016-08-10T202649611-0700 imported 6 documents

httpsriptutorialcomkomongodbtopic6290---

httpsriptutorialcomkohome 36

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 44: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

15

Examples

mongod mongodump

mongodump --db mydb --gzip --out mydbdump$(date +F_R)

mongod mydb bson gzipped mydbdump timestamp

mongod mongorestore

mongorestore --db mydb mydbdump2016-08-27_1244mydb --drop --gzip

mydb mydb mydbdump2016-08-27_12 44 mydb gzipped bson

httpsriptutorialcomkomongodbtopic6494---

httpsriptutorialcomkohome 37

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 45: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

16 ()

Examples

()

dbcollectionfind()

(MYSQL WHERE )

dbcollectionfind(key value) example dbusersfind(emailsampleemailcom)

( )

AND dbcollectionfind( $and [ key value key value ] ) OR dbcollectionfind( $or [ key value key value ] ) NOT dbinventoryfind( key $not value )

find () find () )

FindOne ()

dbcollectionfindOne()

find () findOne () mongodb api documentation

- AND OR IN

students

gt dbstudentsfind()pretty() _id ObjectId(58f29a694117d1b7af126dca)

httpsriptutorialcomkohome 38

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 46: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students

dbstudentsfind(firstNameProsen) _id ObjectId(58f2547804951ad51ad206f5) studentNo 1 firstName Prosen lastName Ghosh age 23

mySql

SELECT FROM students WHERE firstName = Prosen

dbstudentsfind( firstName Prosen age $gte 23 ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

httpsriptutorialcomkohome 39

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 47: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

mySql

SELECT FROM students WHERE firstName = Prosen AND age gt= 23

dbstudentsfind( $or [ firstName Prosen age $gte 23 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23 _id ObjectId(58f29a694117d1b7af126dcd) studentNo 4 firstName Jabed lastName Bangali age 25 _id ObjectId(58f29a694117d1b7af126dce) studentNo 5 firstName Gm lastName Anik age 23

mySql

SELECT FROM students WHERE firstName = Prosen OR age gt= 23

OR

dbstudentsfind( firstName Prosen $or [ age 23 age 25 ] ) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25

mySql

SELECT FROM students WHERE firstName = Prosen AND age = 23 OR age = 25

IN OR

dbstudentsfind(lastName$in[Ghosh Amin]) _id ObjectId(58f29a694117d1b7af126dca) studentNo 1 firstName Prosen lastName Ghosh age 25 _id ObjectId(58f29a694117d1b7af126dcb) studentNo 2 firstName Rajib lastName Ghosh age 25

httpsriptutorialcomkohome 40

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 48: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

_id ObjectId(58f29a694117d1b7af126dcc) studentNo 3 firstName Rizve lastName Amin age 23

mySql

select from students where lastName in (Ghosh Amin)

find ()

find()

gt dbCOLLECTION_NAMEfind(KEY1)

dbpeoplefind(age 0)

Find ()

MongoDB

find()

gt dbCOLLECTION_NAMEfind(KEY1)

gt dbpeoplefind(age0)

gt dbpeoplefind(age1)

_id find() 0

gt dbpeoplefind(name1_id0)

1 0

find ()

find ()

dbtestinsertMany([ nameAny age21 statusbusy nameTony age25 statusbusy nameBobby age28 statusonline nameSonny age28 statusaway nameCher age20 statusonline ])

httpsriptutorialcomkohome 41

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 49: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

dbtestfind()

_id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy _id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()skip(3)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

dbtestfind()sort( name -1)

_id ObjectId(592516d7fbd5b591f53237b1) name Tony age 25 status busy _id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online _id ObjectId(592516d7fbd5b591f53237b2) name Bobby age 28 status online _id ObjectId(592516d7fbd5b591f53237b0) name Any age 21 status busy

-1 1

dbtestfind()count()

httpsriptutorialcomkohome 42

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 50: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

5

1 2

dbtestfind()sort( name -1)skip(1)limit(2)

_id ObjectId(592516d7fbd5b591f53237b3) name Sonny age 28 status away _id ObjectId(592516d7fbd5b591f53237b4) name Cher age 20 status online

() httpsriptutorialcomkomongodbtopic9271----

httpsriptutorialcomkohome 43

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 51: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

17

Examples

show dbs

dbadminCommand(listDatabases)

dbgetMongo()getDBNames()

show collections

show tables

dbgetCollectionNames()

httpsriptutorialcomkomongodbtopic6397--

httpsriptutorialcomkohome 44

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 52: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

18

Examples

3

mongod

mkdir srvmongodbdatars0-0 mkdir srvmongodbdatars0-1 mkdir srvmongodbdatars0-2

mongod

mongod --port 27017 --dbpath srvmongodbdatars0-0 --replSet rs0 mongod --port 27018 --dbpath srvmongodbdatars0-1 --replSet rs0 mongod --port 27019 --dbpath srvmongodbdatars0-2 --replSet rs0

mongo --port 27017 connection to the instance 27017 rsinitiate() initilization of replica set on the 1st node rsadd(lthostnamegt27018) adding a 2nd node rsadd(lthostnamegt27019) adding a 3rd node

rsstatus()

set rs0 date ISODate(2016-09-01T123424968Z) myState 1 term NumberLong(4) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name lthostnamegt27017 health 1 state 1 stateStr PRIMARY _id 1 name lthostnamegt27018 health 1 state 2 stateStr SECONDARY

httpsriptutorialcomkohome 45

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 53: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

_id 2 name lthostnamegt27019 health 1 state 2 stateStr SECONDARY ] ok 1

httpsriptutorialcomkomongodbtopic6205

httpsriptutorialcomkohome 46

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 54: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

19

Examples

Mongodb

mongodb 3

mongodb 3 3 mongodb

mongodb

(mongodb )1

- mkdir cdataserver1 (datafile path for instance 1) - mkdir cdataserver2 (datafile path for instance 2) - mkdir cdataserver3 (datafile path for instance 3)

mongod 2

Enter bull

mongod --replSet s0 --dbpath cdataserver1 --port 37017 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37017 mongodb

Mongodb 2

mongod --replSet s0 --dbpath cdataserver2 --port 37018 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 37018 mongodb 100MB

Mongodb 2

mongod --replSet s0 --dbpath cdataserver3 --port 37019 --smallfiles --oplogSize 100

mongodb replicaSet s0 oplogSize 100MB 37019 mongodb

3 config

3a mongo mongod

mongo --port 37017

mongo config

var config = _ids0 members[]

httpsriptutorialcomkohome 47

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 55: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

2

_id ( s0)1 members [] ( mongod push 2

bull

3b mongod config members push ()

configmemberspush(_id0hostlocalhost37017) configmemberspush(_id1hostlocalhost37018) configmemberspush(_id2hostlocalhost37019)

mongod _id _id

mongo config 4

rsinitiate(config)

3 mongod 5

rsstatus()

httpsriptutorialcomkomongodbtopic6603--

httpsriptutorialcomkohome 48

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 56: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

20

Examples

MongoDB Replica Set

rsstatus ()

set ReplicaName date ISODate(2016-09-26T073604935Z) myState 1 term NumberLong(-1) heartbeatIntervalMillis NumberLong(2000) members [ _id 0 name ltIPgtltPORTgt health 1 state 1 stateStr PRIMARY uptime 5953744 optime Timestamp(1474875364 36) optimeDate ISODate(2016-09-26T073604Z) electionTime Timestamp(1468921646 1) electionDate ISODate(2016-07-19T094726Z) configVersion 6 self true _id 1 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 5953720 optime Timestamp(1474875364 13) optimeDate ISODate(2016-09-26T073604Z) lastHeartbeat ISODate(2016-09-26T073604244Z) lastHeartbeatRecv ISODate(2016-09-26T073603871Z) pingMs NumberLong(0) syncingTo 109525510050 configVersion 6 _id 2 name ltIPgtltPORTgt health 1 state 7

httpsriptutorialcomkohome 49

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 57: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

stateStr ARBITER uptime 5953696 lastHeartbeat ISODate(2016-09-26T073603183Z) lastHeartbeatRecv ISODate(2016-09-26T073603715Z) pingMs NumberLong(0) configVersion 6 _id 3 name ltIPgtltPORTgt health 1 state 2 stateStr SECONDARY uptime 1984305 optime Timestamp(1474875361 16) optimeDate ISODate(2016-09-26T073601Z) lastHeartbeat ISODate(2016-09-26T073602921Z) lastHeartbeatRecv ISODate(2016-09-26T073603793Z) pingMs NumberLong(22) lastHeartbeatMessage syncing from 109525610050 syncingTo 109525610050 configVersion 6 ] ok 1

httpsriptutorialcomkomongodbtopic7043--

httpsriptutorialcomkohome 50

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 58: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

21 dbcollectioncreateIndex( ltstring fieldgt lt1|-1 ordergt [ ltstring fieldgt lt1|-1 ordergt] )

bull

Examples

dbpeoplecreateIndex(name 1)

mongo

dbpeoplecreateIndex(name 1 age -1)

name age name age

name age name name age age

dbpeopledropIndex(nameIndex)

dbpeopledropIndex(name 1)

dbpeoplegetIndexes()

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

getIndexes()

dbtransactionsgetIndexes()

httpsriptutorialcomkohome 51

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 59: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions ]

MongoDB _id _id _id _id

cr_dr

dbtransactionscreateIndex( cr_dr 1 )

createdCollectionAutomatically false numIndexesBefore 1 numIndexesAfter 2 ok 1

createdCollection MongoDB

dbtransactionsgetIndexes() dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions ]

_id cr_dr_1 MongoDB

dbtransactionscreateIndex( cr_dr -1 name index on cr_dr desc)

httpsriptutorialcomkohome 52

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 60: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

dbtransactionsgetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

cr_dr -1 ascending descending -1

24

gt dbtransactionscreateIndex( cr_dr hashed ) gt dbtransactionsgetIndexes( [ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr hashed name cr_dr_hashed ns documentation_dbtransactions ]

httpsriptutorialcomkohome 53

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 61: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

dbcollectiondropIndex(name_of_index)

dbcollectiondropIndex( name_of_field -1 )

dbcollectiongetIndexes()

[ v 1 key _id 1 name _id_ ns documentation_dbtransactions v 1 key cr_dr 1 name cr_dr_1 ns documentation_dbtransactions v 1 key cr_dr -1 name index on cr_dr desc ns documentation_dbtransactions ]

dbcollectioncreateIndex( user_id 1 unique true )

( ) sparse true ( null )

_id johnexamplecom nickname Johnnie _id janeexamplecom _id juliaexamplecom nickname Jules _id jackexamplecom

httpsriptutorialcomkohome 54

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 62: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

null null

dbscorescreateIndex( nickname 1 unique true sparse true )

null

10

dbscoresfind(nickname Johnnie)

( 32 )

dbrestaurantscreateIndex( cuisine 1 partialFilterExpression rating $gt 5 )

rating 5 cuisine

dbcontactscreateIndex( name 1 partialFilterExpression name $exists true )

partialFilterExpression

httpsriptutorialcomkomongodbtopic3934

httpsriptutorialcomkohome 55

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 63: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

22

Examples

3

1

2

3

mongod conf

sharding clusterRole configsvr replication replSetName ltsetnamegt

mongod --config

config

MongoS Setup Mongos

mongos conf

sharding configDB ltconfigReplSetNamegtcfg1examplenet27017

mongos (mongo --host --port)

shaddShard ( s1-mongo1examplenet27017)1 shenableSharding ( )2 shshardCollection ( ltdatabasegt ltcollectiongt ltkeygt ltdirectiongt)3 shstatus () 4

httpsriptutorialcomkomongodbtopic7044-

httpsriptutorialcomkohome 56

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 64: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

23 $ ltfield1gt ltvalue1gt ltfield2gt ltvalue2gt bull

name Tom

targetVaule name Tom

$ set $

Examples

$ set

I

MongoDB RDBMS MongoDB update update

()

M F RDBMS

dbstudentupdate( name Tom query criteria sex F update action )

httpsriptutorialcomkohome 57

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 65: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

update MongoDB

III $

Tom sex $set

dbstudentupdate( name Tom query criteria $set sex F update action )

$set

$set

dbstudentupdate( name Tom query criteria $set sex F age 40 update action

httpsriptutorialcomkohome 58

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 66: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

)

httpsriptutorialcomkomongodbtopic5880-

httpsriptutorialcomkohome 59

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 67: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

24

Examples

find(query)projection(fields)cursorType(CursorTypeTailableAwait)iterator()

MongoCollection

CursorType

Tailable TailableAwait

(lt30) DBCursor addOption

BytesQUERYOPTION_TAILABLE BytesQUERYOPTION_AWAITDATA

password123 dev

MongoClient mongo = new MongoClient(localhost 27017) MongoDatabase db = mongogetDatabase(testDB) MapltString Objectgt commandArguments = new BasicDBObject() commandArgumentsput(createUser dev) commandArgumentsput(pwd password123) String[] roles = readWrite commandArgumentsput(roles roles) BasicDBObject command = new BasicDBObject(commandArguments) dbrunCommand(command)

testdb testcollection name=dev

import orgbsonDocument import commongodbBasicDBObject import commongodbMongoClient import commongodbServerAddress import commongodbclientMongoCollection import commongodbclientMongoCursor import commongodbclientMongoDatabase MongoClient mongoClient = new MongoClient(new ServerAddress(localhost 27017)) MongoDatabase db = mongoClientgetDatabase(testdb) MongoCollectionltDocumentgt collection = dbgetCollection(testcollection) BasicDBObject searchQuery = new BasicDBObject() searchQueryput(namedev) MongoCursorltDocumentgt cursor = collectionfind(searchQuery)iterator() try

httpsriptutorialcomkohome 60

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 68: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

while (cursorhasNext()) Systemoutprintln(cursornext()toJson()) finally cursorclose()

httpsriptutorialcomkomongodbtopic6286-

httpsriptutorialcomkohome 61

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 69: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

25 Aggregations MongoDB map-reduce

Mongo ( httpsdocsmongodbcommanualaggregation)

dbcollectionaggregate ( )bull

( )

( )

MongoDB SQL GROUP BY

transactions

gt dbtransactionsinsert( cr_dr D amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 100 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 2) gt dbtransactionsinsert( cr_dr D amount 100 fee 4) gt dbtransactionsinsert( cr_dr D amount 10 fee 2) gt dbtransactionsinsert( cr_dr C amount 10 fee 4) gt dbtransactionsinsert( cr_dr D amount 100 fee 2)

Examples

count()

gt dbtransactionscount(cr_dr D)

gt dbtransactionsfind(cr_dr D)length()

cr_dr upfront cr_dr Aggregation

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction Add 1 for each document to the count for this type of transaction count $sum 1 ] )

httpsriptutorialcomkohome 62

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 70: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

_id C count 3 _id D count 5

amount

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 counts the number totalAmount $sum $amount sums the amount ] )

_id C count 30 totalAmount 1200 _id D count 50 totalAmount 4100

amount fee

gt dbtransactionsaggregate( [ $group _id $cr_dr count $sum 1 totalAmount $sum $sum [$amount $fee] ] )

_id C count 30 totalAmount 1280

httpsriptutorialcomkohome 63

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 71: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

_id D count 50 totalAmount 4220

gt dbtransactionsaggregate( [ $group _id $cr_dr group by type of transaction (debit or credit) count $sum 1 number of transaction for each type totalAmount $sum $sum [$amount $fee] sum averageAmount $avg $sum [$amount $fee] average ] )

_id C Amounts for credit transactions count 30 totalAmount 1280 averageAmount 400 _id D Amounts for debit transactions count 50 totalAmount 4220 averageAmount 820

unwind

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] dbinventoryaggregate( [ $unwind $sizes ] )

mongo 32 unwind preserveNullAndEmptyArrays

_id 1 item myItem1 sizes [ S M L] _id 2 item myItem2 sizes [ XS M XL] _id 3 item myItem3 dbinventoryaggregate( [ $unwind path $sizes includeArrayIndex arrayIndex ] )

httpsriptutorialcomkohome 64

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 72: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

$ 70000 35

$ 70000 eg average_age $ avg $ match $ group aggregates $ match aggregate average_age average 35

dbemployeesaggregate([ $match salary $lte 70000 $group _id $dept average_age $avg $age $match average_age $gte 35 ])

_id IT average_age 31 _id Customer Service average_age 345 _id Finance average_age 325

( )

allowDiskUse true

var duplicates = [] dbtransactionsaggregate([ $group _id cr_dr $cr_dr dups $addToSet $_id count $sum 1 $match count $gt 1 ]allowDiskUse true ) result forEach(function(doc) docdupsshift() docdupsforEach( function(dupId) duplicatespush(dupId) ) ) printjson(duplicates)

httpsriptutorialcomkohome 65

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 73: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

Remove all duplicates in one go dbtransactionsremove(_id$induplicates)

httpsriptutorialcomkomongodbtopic3852

httpsriptutorialcomkohome 66

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 74: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

26

Examples

gt use mydb switched to db mydb

dbcreateCollection(yourCollectionName) Collection

gt dbcreateCollection(newCollection1) ok 1

show collections

gt show collections newCollection1 systemindexes gt

dbcreateCollection()

fllowing createCollection()

gtdbcreateCollection(newCollection4 capped true autoIndexId true size 6142800 max 10000) ok 1

dbcollectioninsert() dbcollectioncreateIndex()

gt dbnewCollection2insert(name XXX) gt dbnewCollection3createIndex(accountNo 1)

Show show collections show collections

gt show collections newCollection1 newCollection2 newCollection3 newCollection4 systemindexes

httpsriptutorialcomkohome 67

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 75: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

find()

gt dbnewCollection2find() _id ObjectId(58f26876cabafaeb509e9c1f) name XXX

MongoDB dbcollectiondrop()

mydb

gt use mydb switched to db mydb gt show collections newCollection1 newCollection2 newCollection3 systemindexes

newCollection1

gt dbnewCollection1drop() true

true false

gt show collections newCollection2 newCollection3 systemindexes

MongoDB drop ()

httpsriptutorialcomkomongodbtopic9732

httpsriptutorialcomkohome 68

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 76: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

27 mongodb [username password ] host1 [ port1] [ host2 [ port2] [ hostN [ portN]]] [ [database] [ ]]

bull

hostX

portX 27017

database

Examples

pymongo MongoDB

from pymongo import MongoClient uri = mongodblocalhost27017 client = MongoClient(uri) db = client[test_db] or db = clienttest_db collection = db[test_collection] or collection = dbtest_collection collectionsave(helloworld) print collectionfind_one()

PyMongo

collection mongo

dbfind(frequencies $exists true)

pymongo ( True )

dbfind(frequencies $exists True )

bull

bull

httpsriptutorialcomkohome 69

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 77: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

ids ISODate PyMongo ObjectId ID datetime 2010 2011

from datetime import datetime date_from = datetime(2010 1 1) date_to = datetime(2011 1 1) dbfind( date $gte date_from $lt date_to )

PyMongo

import pymongo client = pymongoMongoClient(localhost 27017) db = clientmydbmycollection for doc in dbfind() dbupdate( _id doc[_id] $set newField 10 upsert=False multi=False)

find for in Cursor update _id ( $set ) upsert multi MongoDB ( )

httpsriptutorialcomkomongodbtopic7843-

httpsriptutorialcomkohome 70

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 78: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

S No

Contributors

1 MongoDB

Abdul Rehman Sayed Amir Rahimi Farahani Ashari Community ipip jengeb manetsus Peter Mortensen Prosen Ghosh Renukaradhya Scott Weldon Sean Reilly Simulant titogeo WAF

2 2dsphere gypsyCoder

3 CRUD

fracz Himavanth Ishan Soni Jain jerry JohnnyHK Kelum Senanayake KrisVos130 Lakmal Vithanage Marco Mayank Pandeyz Prosen Ghosh Renukaradhya Rick Rotem Shrabanee sstyvane Thomas Bormans Tomaacutes Cantildeibano

4MongoDB - TLS SSL ReplicaSet

bappr

5 MongoDB Ravi Chandra

6 MongoDB Antti_M

7 MongoDB Niroshan Ranapathi

8 MongoDB Andrii Abramov Avindu Hewa Erdenezul saurav

9 MongoDB Luzan Baral Niroshan Ranapathi

10Pluggable Storage Engine

Constantin Guay Jorge Aranda tim Zanon

11 Upserts Kuhan

12 Matt Clark

13 chridam

14 user641887

15 () Avindu Hewa oggo Prosen Ghosh SommerEngineering

16 fracz

17 ADIMO

18 user641887

Adam Comerford Batsu Constantin Guay jerry Juan Carlos Farah manetsus Nic Cottrell RaR Rick Sarthak Adhikari

19

httpsriptutorialcomkohome 71

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧
Page 79: MongoDB - RIP Tutorial · mongodb_node_1.pem - mongodb_node_2.pem - mongodb_node_3.pem ReplicaSet pem data / data1, data / data2 data / data3 . 27017, 27018 27019 3 ReplicaSet . mongod

titogeo Tomaacutes Cantildeibano

20 Selva Kumar

21 yellowB

22 dev ツ Emil Burzo

23grape HoefMeistert Lakmal Vithanage LoicM manetsus RaR steveinatorx titogeo

24 Prosen Ghosh

25 Derlin sergiuz

httpsriptutorialcomkohome 72

  • 장 1 MongoDB 시작하기
    • 비고
    • 버전
    • Examples
      • 설치
      • 안녕하세요 세계
      • 보완 조항
      • MongoDB에서 JavaScript 파일 실행
      • 쉘에서 읽을 수있는 검색 결과를 출력하기
      • 몽고 셸 기본 명령
          • 장 2 2dsphere 색인
            • Examples
              • 2dsphere 색인 만들기
                  • 장 3 CRUD 작업
                    • 통사론
                    • 비고
                    • Examples
                      • 몹시 떠들어 대다
                      • 최신 정보
                      • 지우다
                      • 독서
                      • 더 많은 업데이트 연산자
                      • 여러 문서를 업데이트하는 동안 multi매개 변수
                      • 삽입 된 문서의 업데이트
                          • 장 4 MongoDB - TLS SSL을 지원하도록 ReplicaSet 구성
                            • 소개
                            • Examples
                              • TLS SSL을 지원하도록 ReplicaSet을 구성하는 방법
                                • 루트 인증서 만들기
                                • 인증서 요청 및 개인 키 생성
                                • 인증서 요청 서명
                                • 키로 각 노드 인증서를 연결하십시오
                                • ReplicaSet 배포
                                • 상호 SSL 상호 트러스트를위한 ReplicaSet 배포
                                  • 클라이언트 (Mongo Shell)를 ReplicaSet에 연결하는 방법은 무엇입니까
                                    • 상호 SSL 없음
                                    • 상호 SSL 사용
                                      • 장 5 MongoDB 관리
                                        • Examples
                                          • 현재 실행중인 쿼리 나열
                                              • 장 6 MongoDB 버전 업그레이드
                                                • 소개
                                                • 비고
                                                • Examples
                                                  • apt를 사용하여 우분투 1604에서 34로 업그레이드
                                                      • 장 7 MongoDB 인증 모델
                                                        • 소개
                                                        • Examples
                                                          • 빌드 기능
                                                              • 장 8 MongoDB 집계
                                                                • Examples
                                                                  • 작업 및 학습에 유용한 집계 쿼리 예제
                                                                  • Java 및 Spring 예제
                                                                  • 샘플 데이터 가져 오기
                                                                  • 집계가있는 왼쪽 외부 조인 ($ Lookup)
                                                                      • 장 9 MongoDB의 인증 메커니즘
                                                                        • 소개
                                                                        • Examples
                                                                          • 인증 메커니즘
                                                                              • 장 10 Pluggable Storage Engine
                                                                                • 비고
                                                                                • Examples
                                                                                  • MMAP
                                                                                  • WiredTiger
                                                                                    • WiredTiger 엔진 사용 방법
                                                                                      • 메모리 내
                                                                                      • 몽고 바위
                                                                                      • 융합 - io
                                                                                      • TokuMX
                                                                                          • 장 11 Upserts 및 삽입물
                                                                                            • Examples
                                                                                              • 문서 삽입
                                                                                                  • 장 12 구성
                                                                                                    • 매개 변수
                                                                                                    • Examples
                                                                                                      • 특정 설정 파일로 mongo 시작하기
                                                                                                          • 장 13 대량 작업
                                                                                                            • 비고
                                                                                                            • Examples
                                                                                                              • 필드를 다른 유형으로 변환하고 전체 모음을 대량으로 업데이트
                                                                                                                  • 장 14 데이터 백업 및 복원
                                                                                                                    • Examples
                                                                                                                      • JSON으로 mongoimport하기
                                                                                                                      • CSV로 mongoimport하기
                                                                                                                          • 장 15 데이터 백업 및 복원
                                                                                                                            • Examples
                                                                                                                              • 로컬 기본 mongod 인스턴스의 기본 mongodump
                                                                                                                              • 로컬 기본 mongod 덤프의 기본 mongorestore
                                                                                                                                  • 장 16 데이터 쿼리 (시작하기)
                                                                                                                                    • 소개
                                                                                                                                    • Examples
                                                                                                                                      • 발견()
                                                                                                                                      • FindOne ()
                                                                                                                                      • 쿼리 문서 - AND OR 및 IN 조건 사용
                                                                                                                                      • 투영법이있는 find () 메소드
                                                                                                                                      • 투영법으로 Find () 메소드 찾기
                                                                                                                                      • find () 메소드의 결과를 제한 건너 뛰기 정렬 및 계산
                                                                                                                                          • 장 17 데이터베이스 정보 얻기
                                                                                                                                            • Examples
                                                                                                                                              • 모든 데이터베이스 나열
                                                                                                                                              • 데이터베이스의 모든 콜렉션 나열
                                                                                                                                                  • 장 18 복제
                                                                                                                                                    • Examples
                                                                                                                                                      • 3 개의 노드가있는 기본 구성
                                                                                                                                                          • 장 19 복제 세트로 몽고
                                                                                                                                                            • Examples
                                                                                                                                                              • 복제 세트로 Mongodb
                                                                                                                                                                  • 장 20 복제 세트로 몽고
                                                                                                                                                                    • Examples
                                                                                                                                                                      • MongoDB Replica Set 상태 확인
                                                                                                                                                                          • 장 21 색인
                                                                                                                                                                            • 통사론
                                                                                                                                                                            • 비고
                                                                                                                                                                            • Examples
                                                                                                                                                                              • 단일 입력란
                                                                                                                                                                              • 화합물
                                                                                                                                                                              • 지우다
                                                                                                                                                                              • 명부
                                                                                                                                                                              • 색인 생성 기본 사항
                                                                                                                                                                                • 해시 된 색인
                                                                                                                                                                                  • 색인 삭제 삭제
                                                                                                                                                                                  • 컬렉션의 인덱스 가져 오기
                                                                                                                                                                                  • 고유 색인
                                                                                                                                                                                  • 스파 스 인덱스 및 부분 인덱스
                                                                                                                                                                                      • 장 22 샤드로서의 몽고
                                                                                                                                                                                        • Examples
                                                                                                                                                                                          • 샤딩 환경 설정
                                                                                                                                                                                              • 장 23 업데이트 연산자
                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                • 비고
                                                                                                                                                                                                • Examples
                                                                                                                                                                                                  • $ set 연산자를 사용하여 문서의 지정된 필드를 업데이트합니다
                                                                                                                                                                                                      • I 개요
                                                                                                                                                                                                      • 업데이트 운영자를 사용하지 않으면 어떻게 될까요
                                                                                                                                                                                                      • III $ 집합 연산자
                                                                                                                                                                                                      • 장 24 자바 드라이버
                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                          • 커서를 생성합니다
                                                                                                                                                                                                          • 데이터베이스 사용자 만들기
                                                                                                                                                                                                          • 조건에 따라 콜렉션 데이터 가져 오기
                                                                                                                                                                                                              • 장 25 집합
                                                                                                                                                                                                                • 소개
                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                • 비고
                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                  • 카운트
                                                                                                                                                                                                                  • 합집합
                                                                                                                                                                                                                  • 평균
                                                                                                                                                                                                                  • 배열 작업
                                                                                                                                                                                                                  • 시합
                                                                                                                                                                                                                  • 컬렉션에서 중복 입력란이있는 문서 삭제 (중복 제거)
                                                                                                                                                                                                                      • 장 26 컬렉션
                                                                                                                                                                                                                        • 비고
                                                                                                                                                                                                                        • Examples
                                                                                                                                                                                                                          • 컬렉션 만들기
                                                                                                                                                                                                                          • 컬렉션 드롭
                                                                                                                                                                                                                              • 장 27 파이썬 드라이버
                                                                                                                                                                                                                                • 통사론
                                                                                                                                                                                                                                • 매개 변수
                                                                                                                                                                                                                                • Examples
                                                                                                                                                                                                                                  • pymongo를 사용하여 MongoDB에 연결
                                                                                                                                                                                                                                  • PyMongo 쿼리
                                                                                                                                                                                                                                  • PyMongo를 사용하여 컬렉션의 모든 문서 업데이트
                                                                                                                                                                                                                                      • 크레딧