关闭

关闭

封号提示

内容

首页 MongoDB and Python.2011.pdf

MongoDB and Python.2011.pdf

MongoDB and Python.2011.pdf

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

简介:本文档为《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

类似资料

该用户的其他资料

MongoDB The Definitive Guide MongoDB权威指南[中文].pdf

professional nosql.2011.pdf

HBase The Definitive Guide.2011.pdf

MongoDB The Definitive Guide.2010.pdf

Redis Cookbook.2011.pdf

职业精品

精彩专题

中秋节除了赏月,你还想怎么过?

“仰头望明月,寄情千里光”,算算你有多久没回家了。庆幸这个中秋节赶上了国庆节,不用悲伤“故乡再无春夏,只有秋冬”,独自一人赏月,8天长假,回家一趟,妥妥的!

用户评论

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

精选资料

热门资料排行换一换

  • 制药企业洁净区人员行为规范要求T…

  • 三命指迷.pdf

  • 中成药的使用、选择、区别以及误区…

  • 少林气功内劲一指禅功法(王瑞亭)…

  • 大雁气功教程.pdf

  • HGT 4343-2012 水性…

  • 黑狐狸.pdf

  • 狄公案——四漆屏.pdf

  • 狄公案-迷宫案.pdf

  • 资料评价:

    / 66
    所需积分:0 立即下载

    意见
    反馈

    返回
    顶部