MongoDBiAbouttheTutorialMongoDBisanopen-sourcedocumentdatabaseandleadingNoSQLdatabase.
MongoDBiswritteninC++.
ThistutorialwillgiveyougreatunderstandingonMongoDBconceptsneededtocreateanddeployahighlyscalableandperformance-orienteddatabase.
AudienceThistutorialisdesignedforSoftwareProfessionalswhoarewillingtolearnMongoDBDatabaseinsimpleandeasysteps.
ItwillthrowlightonMongoDBconceptsandaftercompletingthistutorialyouwillbeatanintermediatelevelofexpertise,fromwhereyoucantakeyourselfathigherlevelofexpertise.
PrerequisitesBeforeproceedingwiththistutorial,youshouldhaveabasicunderstandingofdatabase,texteditorandexecutionofprograms,etc.
Becausewearegoingtodevelophighperformancedatabase,soitwillbegoodifyouhaveanunderstandingonthebasicconceptsofDatabase(RDBMS).
Copyright&DisclaimerCopyright2018byTutorialsPoint(I)Pvt.
Ltd.
Allthecontentandgraphicspublishedinthise-bookarethepropertyofTutorialsPoint(I)Pvt.
Ltd.
Theuserofthise-bookisprohibitedtoreuse,retain,copy,distributeorrepublishanycontentsorapartofcontentsofthise-bookinanymannerwithoutwrittenconsentofthepublisher.
Westrivetoupdatethecontentsofourwebsiteandtutorialsastimelyandaspreciselyaspossible,however,thecontentsmaycontaininaccuraciesorerrors.
TutorialsPoint(I)Pvt.
Ltd.
providesnoguaranteeregardingtheaccuracy,timelinessorcompletenessofourwebsiteoritscontentsincludingthistutorial.
Ifyoudiscoveranyerrorsonourwebsiteorinthistutorial,pleasenotifyusatcontact@tutorialspoint.
comMongoDBiiTableofContentsAbouttheTutorialiAudience.
iPrerequisites.
iCopyright&Disclaimer.
iTableofContents.
iiMONGODB.
11.
MongoDBOverview22.
MongoDBAdvantages.
43.
MongoDBEnvironment.
54.
MongoDBDataModelling105.
MongoDBCreateDatabase126.
MongoDBDropDatabase.
137.
MongoDBCreateCollection148.
MongoDBDropCollection.
169.
MongoDBDatatypes1710.
MongoDBInsertDocument.
1811.
MongoDBQueryDocument2012.
MongoDBUpdateDocument2413.
MongoDBDeleteDocument.
2614.
MongoDBProjection2815.
MongoDBLimitRecords2916.
MongoDBSortRecords3117.
MongoDBIndexing.
3218.
MongoDBAggregation3419.
MongoDBReplication.
3820.
MongoDBSharding.
4121.
MongoDBCreateBackup.
43MongoDBiii22.
MongoDBDeployment.
4523.
MongoDBJava.
4824.
MongoDBPHP.
60ADVANCEDMONGODB.
6625.
MongoDBRelationships6726.
MongoDBDatabaseReferences7027.
MongoDBCoveredQueries7228.
MongoDBAnalyzingQueries7429.
MongoDBAtomicOperations.
7630.
MongoDBAdvancedIndexing7831.
MongoDBIndexingLimitations8032.
MongoDBObjectId.
8133.
MongoDBMapReduce.
8334.
MongoDBTextSearch8635.
MongoDBRegularExpression.
8836.
MongoDBRockMongo.
9037.
MongoDBGridFS9138.
MongoDBCappedCollections9339.
MongoDBAuto-IncrementSequence95MongoDB4MongoDBMongoDB5MongoDBisacross-platform,documentorienteddatabasethatprovides,highperformance,highavailability,andeasyscalability.
MongoDBworksonconceptofcollectionanddocument.
DatabaseDatabaseisaphysicalcontainerforcollections.
Eachdatabasegetsitsownsetoffilesonthefilesystem.
AsingleMongoDBservertypicallyhasmultipledatabases.
CollectionCollectionisagroupofMongoDBdocuments.
ItistheequivalentofanRDBMStable.
Acollectionexistswithinasingledatabase.
Collectionsdonotenforceaschema.
Documentswithinacollectioncanhavedifferentfields.
Typically,alldocumentsinacollectionareofsimilarorrelatedpurpose.
DocumentAdocumentisasetofkey-valuepairs.
Documentshavedynamicschema.
Dynamicschemameansthatdocumentsinthesamecollectiondonotneedtohavethesamesetoffieldsorstructure,andcommonfieldsinacollection'sdocumentsmayholddifferenttypesofdata.
ThefollowingtableshowstherelationshipofRDBMSterminologywithMongoDB.
RDBMSMongoDBDatabaseDatabaseTableCollectionTuple/RowDocumentcolumnFieldTableJoinEmbeddedDocumentsPrimaryKeyPrimaryKey(Defaultkey_idprovidedbymongodbitself)DatabaseServerandClientMysqld/Oraclemongod1.
MongoDBOverviewMongoDB6mysql/sqlplusmongoSampleDocumentFollowingexampleshowsthedocumentstructureofablogsite,whichissimplyacommaseparatedkeyvaluepair.
{_id:ObjectId(7df78ad8902c)title:'MongoDBOverview',description:'MongoDBisnosqldatabase',by:'tutorialspoint',url:'http://www.
tutorialspoint.
com',tags:['mongodb','database','NoSQL'],likes:100,comments:[{user:'user1',message:'Myfirstcomment',dateCreated:newDate(2011,1,20,2,15),like:0},{user:'user2',message:'Mysecondcomments',dateCreated:newDate(2011,1,25,7,45),like:5}]}_idisa12byteshexadecimalnumberwhichassurestheuniquenessofeverydocument.
Youcanprovide_idwhileinsertingthedocument.
Ifyoudon'tprovidethenMongoDBprovidesauniqueidforeverydocument.
These12bytesfirst4bytesforthecurrenttimestamp,next3bytesformachineid,next2bytesforprocessidofMongoDBserverandremaining3bytesaresimpleincrementalVALUE.
MongoDB7Anyrelationaldatabasehasatypicalschemadesignthatshowsnumberoftablesandtherelationshipbetweenthesetables.
WhileinMongoDB,thereisnoconceptofrelationship.
AdvantagesofMongoDBoverRDBMSSchemaless:MongoDBisadocumentdatabaseinwhichonecollectionholdsdifferentdocuments.
Numberoffields,contentandsizeofthedocumentcandifferfromonedocumenttoanother.
Structureofasingleobjectisclear.
Nocomplexjoins.
Deepquery-ability.
MongoDBsupportsdynamicqueriesondocumentsusingadocument-basedquerylanguagethat'snearlyaspowerfulasSQL.
Tuning.
Easeofscale-out:MongoDBiseasytoscale.
Conversion/mappingofapplicationobjectstodatabaseobjectsnotneeded.
Usesinternalmemoryforstoringthe(windowed)workingset,enablingfasteraccessofdata.
WhyUseMongoDBDocumentOrientedStorage:DataisstoredintheformofJSONstyledocuments.
IndexonanyattributeReplicationandhighavailabilityAuto-shardingRichqueriesFastin-placeupdatesProfessionalsupportbyMongoDBWheretoUseMongoDBBigDataContentManagementandDeliveryMobileandSocialInfrastructure2.
MongoDBAdvantagesMongoDB8UserDataManagementDataHubMongoDB9LetusnowseehowtoinstallMongoDBonWindows.
InstallMongoDBonWindowsToinstallMongoDBonWindows,firstdownloadthelatestreleaseofMongoDBfromhttp://www.
mongodb.
org/downloads.
MakesureyougetcorrectversionofMongoDBdependinguponyourWindowsversion.
TogetyourWindowsversion,opencommandpromptandexecutethefollowingcommand.
C:\>wmicosgetosarchitectureOSArchitecture64-bitC:\>32-bitversionsofMongoDBonlysupportdatabasessmallerthan2GBandsuitableonlyfortestingandevaluationpurposes.
Nowextractyourdownloadedfiletoc:\driveoranyotherlocation.
Makesurethenameoftheextractedfolderismongodb-win32-i386-[version]ormongodb-win32-x86_64-[version].
Here[version]istheversionofMongoDBdownload.
Next,openthecommandpromptandrunthefollowingcommand.
C:\>movemongodb-win64-*mongodb1dir(s)moved.
C:\>IncaseyouhaveextractedtheMongoDBatdifferentlocation,thengotothatpathbyusingcommandcdFOOLDER/DIRandnowruntheabovegivenprocess.
MongoDBrequiresadatafoldertostoreitsfiles.
ThedefaultlocationfortheMongoDBdatadirectoryisc:\data\db.
SoyouneedtocreatethisfolderusingtheCommandPrompt.
Executethefollowingcommandsequence.
C:\>mddataC:\mddata\dbIfyouhavetoinstalltheMongoDBatadifferentlocation,thenyouneedtospecifyanalternatepathfor\data\dbbysettingthepathdbpathinmongod.
exe.
Forthesame,issuethefollowingcommands.
3.
MongoDBEnvironmentMongoDB10Inthecommandprompt,navigatetothebindirectorypresentintheMongoDBinstallationfolder.
SupposemyinstallationfolderisD:\setup\mongodbC:\Users\XYZ>d:D:\>cd"setup"D:\setup>cdmongodbD:\setup\mongodb>cdbinD:\setup\mongodb\bin>mongod.
exe--dbpath"d:\setup\mongodb\data"Thiswillshowwaitingforconnectionsmessageontheconsoleoutput,whichindicatesthatthemongod.
exeprocessisrunningsuccessfully.
NowtoruntheMongoDB,youneedtoopenanothercommandpromptandissuethefollowingcommand.
D:\setup\mongodb\bin>mongo.
exeMongoDBshellversion:2.
4.
6connectingto:test>db.
test.
save({a:1})>db.
test.
find(){"_id":ObjectId(5879b0f65a56a454),"a":1}>ThiswillshowthatMongoDBisinstalledandrunsuccessfully.
NexttimewhenyourunMongoDB,youneedtoissueonlycommands.
D:\setup\mongodb\bin>mongod.
exe--dbpath"d:\setup\mongodb\data"D:\setup\mongodb\bin>mongo.
exeInstallMongoDBonUbuntuRunthefollowingcommandtoimporttheMongoDBpublicGPGkeysudoapt-keyadv--keyserverhkp://keyserver.
ubuntu.
com:80--recv7F0CEB10Createa/etc/apt/sources.
list.
d/mongodb.
listfileusingthefollowingcommand.
echo'debhttp://downloads-distro.
mongodb.
org/repo/ubuntu-upstartdist10gen'|sudotee/etc/apt/sources.
list.
d/mongodb.
listNowissuethefollowingcommandtoupdatetherepositorysudoapt-getupdateMongoDB11NextinstalltheMongoDBbyusingthefollowingcommandapt-getinstallmongodb-10gen=2.
2.
3Intheaboveinstallation,2.
2.
3iscurrentlyreleasedMongoDBversion.
Makesuretoinstallthelatestversionalways.
NowMongoDBisinstalledsuccessfully.
StartMongoDBsudoservicemongodbstartStopMongoDBsudoservicemongodbstopRestartMongoDBsudoservicemongodbrestartTouseMongoDBrunthefollowingcommand.
mongoThiswillconnectyoutorunningMongoDBinstance.
MongoDBHelpTogetalistofcommands,typedb.
help()inMongoDBclient.
Thiswillgiveyoualistofcommandsasshowninthefollowingscreenshot.
MongoDB12MongoDB13MongoDBStatisticsTogetstatsaboutMongoDBserver,typethecommanddb.
stats()inMongoDBclient.
Thiswillshowthedatabasename,numberofcollectionanddocumentsinthedatabase.
Outputofthecommandisshowninthefollowingscreenshot.
MongoDB14DatainMongoDBhasaflexibleschema.
documentsinthesamecollection.
Theydonotneedtohavethesamesetoffieldsorstructure,andcommonfieldsinacollection'sdocumentsmayholddifferenttypesofdata.
SomeconsiderationswhiledesigningSchemainMongoDBDesignyourschemaaccordingtouserrequirements.
Combineobjectsintoonedocumentifyouwillusethemtogether.
Otherwiseseparatethem(butmakesurethereshouldnotbeneedofjoins).
Duplicatethedata(butlimited)becausediskspaceischeapascomparetocomputetime.
Dojoinswhilewrite,notonread.
Optimizeyourschemaformostfrequentusecases.
Docomplexaggregationintheschema.
ExampleSupposeaclientneedsadatabasedesignforhisblog/websiteandseethedifferencesbetweenRDBMSandMongoDBschemadesign.
Websitehasthefollowingrequirements.
Everyposthastheuniquetitle,descriptionandurl.
Everypostcanhaveoneormoretags.
Everyposthasthenameofitspublisherandtotalnumberoflikes.
Everyposthascommentsgivenbyusersalongwiththeirname,message,data-timeandlikes.
Oneachpost,therecanbezeroormorecomments.
InRDBMSschema,designforaboverequirementswillhaveminimumthreetables.
4.
MongoDBDataModellingMongoDB15WhileinMongoDBschema,designwillhaveonecollectionpostandthefollowingstructure:{_id:POST_IDtitle:TITLE_OF_POST,description:POST_DESCRIPTION,by:POST_BY,url:URL_OF_POST,tags:[TAG1,TAG2,TAG3],likes:TOTAL_LIKES,comments:[{user:'COMMENT_BY',message:TEXT,dateCreated:DATE_TIME,like:LIKES},{user:'COMMENT_BY',message:TEXT,dateCreated:DATE_TIME,like:LIKES}]}MongoDB16Sowhileshowingthedata,inRDBMSyouneedtojointhreetablesandinMongoDB,datawillbeshownfromonecollectiononly.
MongoDB17Inthischapter,wewillseehowtocreateadatabaseinMongoDB.
TheuseCommandMongoDBuseDATABASE_NAMEisusedtocreatedatabase.
Thecommandwillcreateanewdatabaseifitdoesn'texist,otherwiseitwillreturntheexistingdatabase.
SyntaxBasicsyntaxofuseDATABASEstatementisasfollows:useDATABASE_NAMEExampleIfyouwanttocreateadatabasewithname,thenuseDATABASEstatementwouldbeasfollows:>usemydbswitchedtodbmydbTocheckyourcurrentlyselecteddatabase,usethecommanddb>dbmydbIfyouwanttocheckyourdatabaseslist,usethecommandshowdbs.
>showdbslocal0.
78125GBtest0.
23012GBYourcreateddatabase(mydb)isnotpresentinlist.
Todisplaydatabase,youneedtoinsertatleastonedocumentintoit.
>db.
movie.
insert({"name":"tutorialspoint"})>showdbslocal0.
78125GBmydb0.
23012GB5.
MongoDBCreateDatabaseMongoDB18test0.
23012GBInMongoDBdefaultdatabaseistest.
Ifyoudidn'tcreateanydatabase,thencollectionswillbestoredintestdatabase.
MongoDB19Inthischapter,wewillseehowtodropadatabaseusingMongoDBcommand.
ThedropDatabase()MethodMongoDBdb.
dropDatabase()commandisusedtodropaexistingdatabase.
SyntaxBasicsyntaxofdropDatabase()commandisasfollows:db.
dropDatabase()Thiswilldeletetheselecteddatabase.
Ifyouhavenotselectedanydatabase,thenitwilldeletedefault'test'database.
ExampleFirst,checkthelistofavailabledatabasesbyusingthecommand,showdbs.
>showdbslocal0.
78125GBmydb0.
23012GBtest0.
23012GB>Ifyouwanttodeletenewdatabase,thendropDatabase()commandwouldbeasfollows:>usemydbswitchedtodbmydb>db.
dropDatabase()>{"dropped":"mydb","ok":1}>Nowchecklistofdatabases.
>showdbslocal0.
78125GBtest0.
23012GB>6.
MongoDBDropDatabaseMongoDB20Inthischapter,wewillseehowtocreateacollectionusingMongoDB.
ThecreateCollection()MethodMongoDBdb.
createCollection(name,options)isusedtocreatecollection.
SyntaxBasicsyntaxofcreateCollection()commandisasfollows:db.
createCollection(name,options)Inthecommand,nameisnameofcollectiontobecreated.
Optionsisadocumentandisusedtospecifyconfigurationofcollection.
ParameterTypeDescriptionNameStringNameofthecollectiontobecreatedOptionsDocument(Optional)SpecifyoptionsaboutmemorysizeandindexingOptionsparameterisoptional,soyouneedtospecifyonlythenameofthecollection.
Followingisthelistofoptionsyoucanuse:FieldTypeDescriptioncappedBoolean(Optional)Iftrue,enablesacappedcollection.
Cappedcollectionisafixedsizecollectionthatautomaticallyoverwritesitsoldestentrieswhenitreachesitsmaximumsize.
Ifyouspecifytrue,youneedtospecifysizeparameteralso.
autoIndexIDBoolean(Optional)Iftrue,automaticallycreateindexon_idfield.
Defaultvalueisfalse.
sizenumber(Optional)Specifiesamaximumsizeinbytesforacappedcollection.
Ifcappedistrue,thenyouneedtospecifythisfieldalso.
7.
MongoDBCreateCollectionMongoDB21maxnumber(Optional)Specifiesthemaximumnumberofdocumentsallowedinthecappedcollection.
Whileinsertingthedocument,MongoDBfirstcheckssizefieldofcappedcollection,thenitchecksmaxfield.
ExamplesBasicsyntaxofcreateCollection()methodwithoutoptionsisasfollows:>usetestswitchedtodbtest>db.
createCollection("mycollection"){"ok":1}>Youcancheckthecreatedcollectionbyusingthecommandshowcollections.
>showcollectionsmycollectionsystem.
indexesThefollowingexampleshowsthesyntaxofcreateCollection()methodwithfewimportantoptions:>db.
createCollection("mycol",{capped:true,autoIndexID:true,size:6142800,max:10000}){"ok":1}>InMongoDB,youdon'tneedtocreatecollection.
MongoDBcreatescollectionautomatically,whenyouinsertsomedocument.
>db.
tutorialspoint.
insert({"name":"tutorialspoint"})>showcollectionsmycolmycollectionsystem.
indexestutorialspoint>MongoDB22EndofebookpreviewIfyoulikedwhatyousaw…Buyitfromourstore@https://store.
tutorialspoint.
com
SoftShellWeb是一家2019年成立的国外主机商,商家在英格兰注册,提供的产品包括虚拟主机和VPS,其中VPS基于KVM架构,采用SSD硬盘,提供IPv4+IPv6,可选美国(圣何塞)、荷兰(阿姆斯特丹)和台湾(台北)等机房。商家近期推出台湾和荷兰年付特价VPS主机,其中台湾VPS最低年付49美元,荷兰VPS年付24美元起。台湾VPSCPU:1core内存:2GB硬盘:20GB SSD流量...
搬瓦工和Vultr哪个好?搬瓦工和Vultr都是非常火爆的国外VPS,可以说是国内网友买的最多的两家,那么搬瓦工和Vultr哪个好?如果要选择VPS,首先我们要考虑成本、服务器质量以及产品的售后服务。老玩家都知道目前在国内最受欢迎的国外VPS服务商vultr和搬瓦工口碑都很不错。搬瓦工和Vultr哪个稳定?搬瓦工和Vultr哪个速度快?为了回答这些问题,本文从线路、速度、功能、售后等多方面对比这两...
bgp.to对日本机房、新加坡机房的独立服务器在搞特价促销,日本独立服务器低至6.5折优惠,新加坡独立服务器低至7.5折优惠,所有优惠都是循环的,终身不涨价。服务器不限制流量,支持升级带宽,免费支持Linux和Windows server中文版(还包括Windows 10). 特色:自动部署,无需人工干预,用户可以在后台自己重装系统、重启、关机等操作!官方网站:https://www.bgp.to...
sources.list为你推荐
TD-SCDMAsns支付宝蜻蜓发布蜻蜓支付可以代理么googleprGoogle PR的值是6.这个是什么意思?cisco2960cisco2960接入层交换机支付宝调整还款日蚂蚁借呗怎么设置还款时间支付宝注册网站在哪里注册支付宝账号Joinsql闪拍网闪拍网之类的网站怎么回事?zhuo爱timi什么意思powerbydedecms织梦dedecms怎么去掉power by dedecms方法
域名解析 tk域名注册 3322动态域名 主机 windows主机 安云加速器 l5639 搬瓦工官网 域名优惠码 lamp配置 ev证书 镇江联通宽带 台湾谷歌网址 亚洲小于500m 40g硬盘 域名转向 七夕快乐英文 服务器是干什么的 美国堪萨斯 1美金 更多