首页 > > MongoDB and Python.2011.pdf

MongoDB and Python.2011.pdf

MongoDB and Python.2011.pdf

上传者: tyhtzwl_fupgu 2012-04-03 评分1 评论0 下载636 收藏10 阅读量991 暂无简介 简介 举报

简介:本文档为《MongoDB and Python.2011pdf》,可适用于领域,主题内容包含MongoDBandPythonNiallO’HigginsBeijing•Cambridge•Farnham•Köln•Sebastopol•To符等。

MongoDBandPythonNiallO’HigginsBeijing•Cambridge•Farnham•Köln•Sebastopol•TokyoMongoDBandPythonbyNiallO’HigginsCopyrightNiallO’HigginsAllrightsreservedPrintedintheUnitedStatesofAmericaPublishedbyO’ReillyMedia,Inc,GravensteinHighwayNorth,Sebastopol,CAO’Reillybooksmaybepurchasedforeducational,business,orsalespromotionaluseOnlineeditionsarealsoavailableformosttitles(http:mysafaribooksonlinecom)Formoreinformation,contactourcorporateinstitutionalsalesdepartment:()orcorporateoreillycomEditors:MikeLoukidesandShawnWallaceProductionEditor:JasminePerezProofreader:O’ReillyProductionServicesCoverDesigner:KarenMontgomeryInteriorDesigner:DavidFutatoIllustrator:RobertRomanoNutshellHandbook,theNutshellHandbooklogo,andtheO’ReillylogoareregisteredtrademarksofO’ReillyMedia,IncMongoDBandPython,theimageofadwarfmongoose,andrelatedtradedressaretrademarksofO’ReillyMedia,IncManyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarksWherethosedesignationsappearinthisbook,andO’ReillyMedia,Incwasawareofatrademarkclaim,thedesignationshavebeenprintedincapsorinitialcapsWhileeveryprecautionhasbeentakeninthepreparationofthisbook,thepublisherandauthorassumenoresponsibilityforerrorsoromissions,orfordamagesresultingfromtheuseoftheinformationcontainedhereinISBN:LSITableofContentsPrefacevGettingStartedIntroductionFindingReferenceDocumentationInstallingMongoDBRunningMongoDBSettingupaPythonEnvironmentwithMongoDBReadingandWritingtoMongoDBwithPythonConnectingtoMongoDBwithPythonGettingaDatabaseHandleInsertingaDocumentintoaCollectionWritetoaCollectionSafelyandSynchronouslyGuaranteeingWritestoMultipleDatabaseNodesIntroductiontoMongoDBQueryLanguageReading,Counting,andSortingDocumentsinaCollectionUpdatingDocumentsinaCollectionDeletingDocumentsfromaCollectionMongoDBQueryOperatorsMongoDBUpdateModifiersCommonMongoDBandPythonPatternsAUniquelyDocumentOrientedPattern:EmbeddingFastLookups:UsingIndexeswithMongoDBLocationbasedAppswithMongoDB:GeoSpatialIndexingCodeDefensivelytoAvoidKeyErrorsandOtherBugsUpdateorInsert:UpsertsinMongoDBAtomicReadWriteModify:MongoDB’sfindAndModifyFastAccountingPatterniiiMongoDBwithWebFrameworksPylonsxandMongoDBPyramidandMongoDBDjangoandMongoDBGoingFurtheriv|TableofContentsPrefaceI’vebeenbuildingproductiondatabasedrivenapplicationsforaboutyearsI’veworkedwithmostoftheusualrelationaldatabases(MSSQLServer,MySQL,PostgreSQL)andwithsomeveryinterestingnonrelationaldatabases(Freebasecom’sGraphdMQL,BerkeleyDB,MongoDB)MongoDBisatthispointthesystemIenjoyworkingwiththemost,andchooseformostprojectsItsitssomewhereatacrossroadsbetweentheperformanceandpragmatismofarelationalsystemandtheflexibilityandexpressivenessofasemanticwebdatabaseIthasbeencentraltomysuccessinbuildingsomequitecomplicatedsystemsinashortperiodoftimeIhopethatafterreadingthisbookyouwillfindMongoDBtobeapleasantdatabasetoworkwith,andonewhichdoesn’tgetinthewaybetweenyouandtheapplicationyouwishtobuildConventionsUsedinThisBookThefollowingtypographicalconventionsareusedinthisbook:ItalicIndicatesnewterms,URLs,emailaddresses,filenames,andfileextensionsConstantwidthUsedforprogramlistings,aswellaswithinparagraphstorefertoprogramelementssuchasvariableorfunctionnames,databases,datatypes,environmentvariables,statements,andkeywordsConstantwidthboldShowscommandsorothertextthatshouldbetypedliterallybytheuserConstantwidthitalicShowstextthatshouldbereplacedwithusersuppliedvaluesorbyvaluesdeterminedbycontextvThisiconsignifiesatip,suggestion,orgeneralnoteThisiconindicatesawarningorcautionUsingCodeExamplesThisbookisheretohelpyougetyourjobdoneIngeneral,youmayusethecodeinthisbookinyourprogramsanddocumentationYoudonotneedtocontactusforpermissionunlessyou’rereproducingasignificantportionofthecodeForexample,writingaprogramthatusesseveralchunksofcodefromthisbookdoesnotrequirepermissionSellingordistributingaCDROMofexamplesfromO’ReillybooksdoesrequirepermissionAnsweringaquestionbycitingthisbookandquotingexamplecodedoesnotrequirepermissionIncorporatingasignificantamountofexamplecodefromthisbookintoyourproduct’sdocumentationdoesrequirepermissionWeappreciate,butdonotrequire,attributionAnattributionusuallyincludesthetitle,author,publisher,andISBNForexample:“MongoDBandPythonbyNiallO’HigginsCopyrightO’ReillyMediaInc,”Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseorthepermissiongivenabove,feelfreetocontactusatpermissionsoreillycomSafariBooksOnlineSafariBooksOnlineisanondemanddigitallibrarythatletsyoueasilysearchover,technologyandcreativereferencebooksandvideostofindtheanswersyouneedquicklyWithasubscription,youcanreadanypageandwatchanyvideofromourlibraryonlineReadbooksonyourcellphoneandmobiledevicesAccessnewtitlesbeforetheyareavailableforprint,andgetexclusiveaccesstomanuscriptsindevelopmentandpostfeedbackfortheauthorsCopyandpastecodesamples,organizeyourfavorites,downloadchapters,bookmarkkeysections,createnotes,printoutpages,andbenefitfromtonsofothertimesavingfeaturesO’ReillyMediahasuploadedthisbooktotheSafariBooksOnlineserviceTohavefulldigitalaccesstothisbookandothersonsimilartopicsfromO’Reillyandotherpublishers,signupforfreeathttp:mysafaribooksonlinecomvi|PrefaceHowtoContactUsPleaseaddresscommentsandquestionsconcerningthisbooktothepublisher:O’ReillyMedia,IncGravensteinHighwayNorthSebastopol,CA(intheUnitedStatesorCanada)(internationalorlocal)(fax)Wehaveawebpageforthisbook,wherewelisterrata,examples,andanyadditionalinformationYoucanaccessthispageat:http:wwworeillycomcatalogTocommentorasktechnicalquestionsaboutthisbook,sendemailto:bookquestionsoreillycomFormoreinformationaboutourbooks,courses,conferences,andnews,seeourwebsiteathttp:wwworeillycomFindusonFacebook:http:facebookcomoreillyFollowusonTwitter:http:twittercomoreillymediaWatchusonYouTube:http:wwwyoutubecomoreillymediaAcknowledgmentsIwouldliketothankArielBackenroth,AseemMohantyandEugeneCiuranaforgivingdetailedfeedbackonthefirstdraftofthisbookIwouldalsoliketothanktheO’ReillyteamformakingitagreatpleasuretowritethebookOfcourse,thankstoallthepeopleatgenwithoutwhomMongoDBwouldnotexistandthisbookwouldnothavebeenpossiblePreface|viiCHAPTERGettingStartedIntroductionFirstreleasedin,MongoDBisrelativelynewonthedatabasescenecomparedtocontemporarygiantslikeOraclewhichtracetheirfirstreleasestothe’sAsadocumentorienteddatabasegenerallygroupedintotheNoSQLcategory,itstandsoutamongdistributedkeyvaluestores,AmazonDynamoclonesandGoogleBigTablereimplementationsWithafocusonrichoperatorsupportandhighperformanceOnlineTransactionProcessing(OLTP),MongoDBisinmanywaysclosertoMySQLthantobatchorienteddatabaseslikeHBaseThekeydifferencesbetweenMongoDB’sdocumentorientedapproachandatraditionalrelationaldatabaseare:MongoDBdoesnotsupportjoinsMongoDBdoesnotsupporttransactionsItdoeshavesomesupportforatomicoperations,howeverMongoDBschemasareflexibleNotalldocumentsinacollectionmustadheretothesameschemaandareadirectresultofthehugedifficultiesinmakingthesefeaturesscaleacrossalargedistributedsystemwhilemaintainingacceptableperformanceTheyaretradeoffsmadeinordertoallowforhorizontalscalabilityAlthoughMongoDBlacksjoins,itdoesintroducesomealternativecapabilites,egembedding,whichcanbeusedtosolvemanyofthesamedatamodelingproblemsasjoinsOfcourse,evenifembeddingdoesn’tquitework,youcanalwaysperformyourjoininapplicationcode,bymakingmultiplequeriesThelackoftransactionscanbepainfulattimes,butfortunatelyMongoDBsupportsafairlydecentsetofatomicoperationsFromthebasicatomicincrementanddecrementoperatorstothericher“findAndModify”,whichisessentiallyanatomicreadmodifywriteoperatorItturnsoutthataflexibleschemacanbeverybeneficial,especiallywhenyouexpecttobeiteratingquicklyWhileupfrontschemadesignasusedintherelationalmodelhasitsplace,thereisoftenaheavycostintermsofmaintenanceHandlingschemaupdatesintherelationalworldisofcoursedoable,butcomeswithapriceInMongoDB,youcanaddnewpropertiesatanytime,dynamically,withouthavingtoworryaboutALTERTABLEstatementsthatcantakehourstorunandcomplicateddatamigrationscriptsHowever,thisapproachdoescomewithitsowntradeoffsForexample,typeenforcementmustbecarefullyhandledbytheapplicationcodeCustomdocumentversioningmightbedesirabletoavoidlargeconditionalblockstohandleheterogeneousdocumentsinthesamecollectionThedynamicnatureofMongoDBlendsitselfquitenaturallytoworkingwithadynamiclanguagesuchasPythonThetradeoffsbetweenadynamicallytypedlanguagesuchasPythonandastaticallytypedlanguagesuchasJavainmanyrespectsmirrorthetradeoffsbetweentheflexible,documentorientedmodelofMongoDBandtheupfrontandstaticallytypedschemadefinitionofSQLdatabasesPythonallowsyoutoexpressMongoDBdocumentsandqueriesnatively,throughtheuseofexistinglanguagefeatureslikenesteddictionariesandlistsIfyouhaveworkedwithJSONinPython,youwillimmediatelybecomfortablewithMongoDBdocumentsandqueriesForthesereasons,MongoDBandPythonmakeapowerfulcombinationforrapid,iterativedevelopmentofhorizontallyscalablebackendapplicationsForthevastmajorityofmodernWebandmobileapplications,webelieveMongoDBislikelyabetterfitthanRDBMStechnologyFindingReferenceDocumentationMongoDB,Python,gen’sPyMongodriverandeachoftheWebframeworksmentionedinthisbookallhavegoodreferencedocumentationonlineForMongoDB,wewouldstronglysuggestbookmarkingandatleastskimmingovertheofficialMongoDBmanualwhichisavailableinafewdifferentformatsandconstantlyupdatedathttp:wwwmongodborgdisplayDOCSManualWhilethemanualdescribestheJavaScriptinterfaceviathemongoconsoleutilityasopposedtothePythoninterface,mostofthecodesnippetsshouldbeeasilyunderstoodbyaPythonprogrammerandmoreorlessportabletoPyMongo,albeitsometimeswithalittlebitofworkFurthermore,theMongoDBmanualgoesintogreaterdepthoncertainadvancedandtechnicalimplementationanddatabaseadministrationtopicsthanispossibleinthisbook|Chapter: GettingStartedForthePythonlanguageandstandardlibrary,youcanusethehelp()functionintheinterpreterorthepydoctoolonthecommandlinetogetAPIdocumentationforanymethodsormodulesForexample:pydocstringThelatestPythonlanguageandAPIdocumentationisalsoavailableforonlinebrowsingathttp:docspythonorggen’sPyMongodriverhasAPIdocumentationavailableonlinetogowitheachreleaseYoucanfindthisathttp:apimongodborgpythonAdditionally,onceyouhavethePyMongodriverpackageinstalledonyoursystem,asummaryversionoftheAPIdocumentationshouldbeavailabletoyouinthePythoninterpreterviathehelp()functionDuetoanissuewiththevirtualenvtoolmentionedinthenextsection,“pydoc”doesnotworkinsideavirtualenvironmentYoumustinsteadrunpythonmpydocpymongoInstallingMongoDBForthepurposesofdevelopment,itisrecommendedtorunaMongoDBserveronyourlocalmachineThiswillpermityoutoiteratequicklyandtrynewthingswithoutfearofdestroyingaproductiondatabaseAdditionally,youwillbeabletodevelopwithMongoDBevenwithoutanInternetconnectionDependingonyouroperatingsystem,youmayhavemultipleoptionsforhowtoinstallMongoDBlocallyMostmodernUNIXlikesystemswillhaveaversionofMongoDBavailableintheirpackagemanagementsystemThisincludesFreeBSD,Debian,Ubuntu,Fedora,CentOSandArchLinuxInstallingoneofthesepackagesislikelythemostconvenientapproach,althoughtheversionofMongoDBprovidedbyyourpackagingvendormaylagbehindthelatestreleasefromgenForlocaldevelopment,aslongasyouhavethelatestmajorrelease,youareprobablyfinegenalsoprovidestheirownMongoDBpackagesformanysystemswhichtheyupdateveryquicklyoneachreleaseThesecanbealittlemoreworktogetinstalledbutensureyouarerunningthelatestandgreatestAftertheinitialsetup,theyaretypicallytrivialtokeepuptodateForaproductiondeployment,whereyoulikelywanttobeabletoupdatetothemostrecentstableMongoDBversionwithaminimumofhassle,thisoptionprobablymakesthemostsenseInadditiontothesystempackageversionsofMongoDB,genprovidebinaryzipandtararchivesTheseareindependentofyoursystempackagemanagerandareprovidedinbothbitandbitflavoursforOSX,Windows,LinuxandSolarisgenalsoprovidestaticallybuiltbinarydistributionsofthiskindforLinux,whichmaybeyourbestoptionifyouarestuckonanolder,legacyLinuxsystemlackingthemodernlibcInstallingMongoDB|andotherlibraryversionsAlso,ifyouareonOSX,WindowsorSolaris,theseareprobablyyourbestbetFinally,youcanalwaysbuildyourownbinariesfromthesourcecodeUnlessyouneedtomakemodificationstoMongoDBinternalsyourself,thismethodisbestavoidedduetothetimeandcomplexityinvolvedIntheinterestsofsimplicity,wewillprovidethecommandsrequiredtoinstallastableversionofMongoDBusingthesystempackagemanagerofthemostcommonUNIXlikeoperatingsystemsThisistheeasiestmethod,assumingyouareononeoftheseplatformsForMacOSXandWindows,weprovideinstructionstoinstallthebinarypackagesfromgenUbuntuDebian:sudoaptgetupdatesudoaptgetinstallmongodbFedora:sudoyuminstallmongostableserverFreeBSD:sudopkgaddrmongodbWindows:Gotohttp:wwwmongodborganddownloadthelatestproductionreleasezipfileforWindowschoosingbitorbitdependingonyoursystemExtractthecontentsofthezipfiletoalocationlikeC:mongodbandaddthebindirectorytoyourPATHMacOSX:Gotohttp:wwwmongodborganddownloadthelatestproductionreleasecompressedtarfileforOSXchoosingbitorbitdependingonyoursystemExtractthecontentstoalocationlikeusrlocaloroptandaddthebindirectorytoyour$PATHForexmaple:cdtmpwgethttp:fastdlmongodborgosxmongodbosxxrctgztarxfzmongodbosxxrctgzsudomkdirusrlocalmongodbsudocprmongodbosxxrcbinusrlocalmongodbexportPATH=$PATH:usrlocalmongodbbin|Chapter: GettingStartedInstallMongoDBonOSXwithMacPortsIfyouwouldliketotryathirdpartysystempackagemanagementsystemonMacOSX,youmayalsoinstallMongoDB(andPython,infact)throughMacPortsMacPortsissimilartoFreeBSDports,butforOSXAwordofwarningthough:MacPortscompilesfromsource,andsocantakeconsiderablylongertoinstallsoftwarecomparedwithsimplygrabbingthebinariesFuthermore,youwillneedtohaveApple’sXcodeDeveloperToolsinstalled,alongwiththeXwindowingenvironmentThefirststepistoinstallMacPortsfromhttp:wwwmacportsorgWerecommenddownloadingandinstallingtheirDMGpackageOnceyouhaveMacPortsinstalled,youcaninstallMongoDBwiththecommand:sudoportselfupdatesudoportinstallmongodbToinstallPythonfromMacPortsusethecommand:sudoportselfupdatesudoportinstallpythonRunningMongoDBOnsomeplatformssuchasUbuntuthepackagemanagerwillautomaticallystartthemongoddaemonforyou,andensureitstartsonbootalsoOnothers,suchasMacOSX,youmustwriteyourownscripttostartit,andmanuallyintegratewithlaunchdsothatitstartsonsystembootNotethatbeforeyoucanstartMongoDB,itsdataandlogdirectoriesmustexistIfyouwishtohaveMongoDBstartautomaticallyonbootonWindows,genhaveadocumentdescribinghowtosetthisupathttp:wwwmongodborgdisplayDOCSWindowsServiceTohaveMongoDBstartautomaticallyonbootunderMacOSX,firstyouwillneedaplistfileSavethefollowing(changingdbandlogpathsappropriately)toLibraryLaunchDaemonsorgmongodbmongodplist:<xmlversion=""encoding=""><!DOCTYPEplistPUBLIC"AppleDTDPLISTEN""http:wwwapplecomDTDsPropertyListdtd"><plistversion=""><dict><key>RunAtLoad<key><true><key>Label<key><string>orgmongomongod<string><key>ProgramArguments<key><array><string>usrlocalmongodbbinmongod<string><string>dbpath<string>RunningMongoDB|<string>usrlocalmongodbdata<string><string>logpath<string><string>usrlocalmongodblogmongodblog<string><array><dict><plist>Nextrunthefollowingcommandstoactivatethestartupscriptwithlaunchd:sudolaunchctlloadLibraryLaunchDaemonsorgmongodbmongodplistsudolaunchctlstartorgmongodbmongodAquickwaytotestwhetherthereisaMongoDBinstancealreadyrunningonyourlocalmachineistotypemongoatthecommandlineThiswillstarttheMongoDBadminconsole,whichattemptstoconnecttoadatabaseserverrunningonthedefaultport()Inanycase,youcanalwaysstartMongoDBmanuallyfromthecommandlineThisisausefulthingtobefamiliarwithincaseyoueverwanttotestfeaturessuchasreplicasetsorshardingbyrunningmultiplemongodinstancesonyourlocalmachineAssumingthemongodbinaryisinyour$PATH,run:mongodlogpath<pathtomongologfile>port<porttolistenon>dbpath<pathtodatadirectory>SettingupaPythonEnvironmentwithMongoDBInordertobeabletoconnecttoMongoDBwithPython,youneedtoinstallthePyMongodriverpackageInPython,thebestpracticeist

精彩专题

热门资料

Word操作技巧大全.pdf

WORD排版教程(完整版).pdf

outlook2007使用手册.pdf

PPT模板精品.ppt

该用户的其他资料

  • 名称/格式
  • 评分
  • 下载次数
  • 资料大小
  • 上传时间

用户评论

0/200
    暂无评论
上传我的资料

相关资料换一换

资料评价:

/ 66
所需积分:0 立即下载
返回
顶部
举报
资料
关闭

温馨提示

感谢您对爱问共享资料的支持,精彩活动将尽快为您呈现,敬请期待!