MongoDB
The
NoSQL
Database for
Cloud
and
Desktop Computing
TECHNISCHE
INFORMATIONSBIBLIO
1HEKUNIVERSITATSBIBLIOTHEK
HANNOVER11 111
Eelco
Plugge,
Peter
Membrey
and
Tim
Hawkins
Apress8
TIB/UB Hannover 89 133 302 342
EContentsata Glance iv
About the Authors xvi About theTechnical Reviewer xvii
Acknowledgments
xviiiIntroduction xx
Part I: Basics 1
Chapter
1: Introduction toMongoDB
3Reviewing
theMongoDB Philosophy
3UsingtheRightToolfor theRightJob 3 LackingInnateSupportfor Transactions 5 DrillingDown onJSON and How It RelatestoMongoDB 5
AdoptingaNon-RelationalApproach 7
Optingfor Performancevs.Features 8
Runningthe DatabaseAnywhere 9
Fitting Everything Together
9GeneratingorCreating aKey 9
Using Keysand Values 10
Implementing Collections 11
UnderstandingDatabases 11
Reviewing
the Feature List 11UsingDocument-OrientatedStorage (BSON) 11
Supporting DynamicQueries 12
IndexingYourDocuments 13
Leveraging GeospatialIndexes • • ••••• • 13
ProfilingQueries •** I4
UpdatingInformation In-Place • .14
Storing BinaryData • • 14
Replicating Data 15
implementingAutoSharding • • -""IS
Using Mapand Reduce Functions 16
Getting
Help
»»• > »• »• »«16Visitingthe Website - 16
Chatting with theMongoDBDevelopers , 16
CuttingandPasting MongoDB Code ...17
FindingSolutionson GoogleGroups 17
LeveragingtheJIRATracking System 17
Summary
17Chapter
2:Installing
MongoDB
... 19Choosing
YourVersion < 19Understandingthe Version Numbers , 20
Installing MongoDB
onYourSystem,...,
...20 Installing MongoDBUnder Linux 20Installing MongoDBUnder Windows 22
Running
MongoDB
, 22Prerequisites 22
Surveyingthe InstallationLayout , 23
UsingtheMongoDBShell... 23
Installing
Additional Drivers 24Installing the PHP driver 25 ConfirmingYour PHP Installation Works 28 Installing the PythonDriver .30
ConfirmingYourPyMongo Installation Works , , 33
HCONTENTS
Summary
33Chapter
3: The Data Model 35Designing
the Database 35DrillingDownonCollections 36
UsingDocuments 38
CreatingthejdField 40
Building
Indexes 41ImpactingPerformance with Indexes 42
Implementing Geospatial Indexing
42 Querying Geospatial Information 43Using
MongoDB
in the Real World 46Summary
46Chapter 4:
Working
with Data 47Navigating
Your Databases 47 ViewingAvailable Databases and Collections 47Inserting
DataintoCollections 48Querying
for Data 49Usingthe Dot Notation 51
UsingtheSort,Limit,andSkip Functions 52
Workingwith Capped Collections, NaturalOrder,and$natural 53
RetrievingaSingleDocument 55
Using the
Aggregation
Commands 55Workingwith Conditional Operators 57
Leveraging Regular Expressions 65
Updating
Data 65Updatingwith updateO 65
ImplementinganUpsertwiththesaveQ Command 66 UpdatingInformationAutomatically 66
Specifyingthe PositionofaMatchedArray 70
Atomic Operations 71 ModifyingandReturningaDocumentAtomically 73
Renaming
a Collection 74Removing
Data 74Referencing
a Database 75Referencing DataManually 75
ReferencingData with DBRef 76
Implementing
Index-Related Functions 78Surveying Index-RelatedCommands 80
Forcing aSpecifiedIndex to QueryData 80 Constraining QueryMatches 80
Summary
81Chapter
5: GridFS „ 83Filling
in SomeBackground
83Working
with GridFS 84Getting
Started with the Command-LineTools 85UsingtheJdKey 86
Working with Filenames 86 DeterminingaFile'sLength 86
Workingwith Chunk Sizes 87 Trackingthe UploadDate 87
HashingYourFiles 87
Looking
UnderMongoDB's
Hood 88Using the Search Command 90
Deleting , , 90
Retrieving FilesfromMongoDB
, 91
Summingupmongofiles , 91
Exploiting
the Power ofPython
91Connectingtothe Database 92
mCONTENTS
AccessingtheWords 93
Putting
Files intoMongoDB
93Retrieving
Files fromGridFS 94Deleting
Files 94Summary
95Part II:
Developing
97Chapter
6: PHP andMongoDB
99Comparing
Documents inMongoDB
and PHP 99MongoDB
Classes 100Connecting
andDisconnecting
101Inserting
Data 102Listing
YourData 104ReturningaSingleDocument 104
ListingAll Documents 105
Using Query Operators 106
Querying forSpecificInformation 106 Sorting, Limiting,andSkippingitems 107
Countingthe Number ofMatching Results 108
GroupingData withMap/Reduce 109
Specifyingthe Index withHint 111
RefiningQueries with Conditional Operators 111
Regular Expressions 118
Modifying
Data with PHP 119UpdatingviaupdateQ 119
SavingTime with ModifierOperators 121
UpsertingData withsave() 125
ModifyingaDocumentAtomically 126
Deleting
Data 129Retrievingthe Information 132
GridFS and the PHP Driver 132 StoringFiles 133
AddingMore Metadata to Stored Files 133
Retrieving Files 134
DeletingData 135
Summary
• 135Chapter
7:Python
andMongoDB
137Working
with DocumentsinPython
137Using PyMongo
Modules 138Connecting
andDisconnecting
138Inserting
Data 139Finding
Your Data 140FindingaSingleDocument 140
FindingMultipleDocuments 141
Using Dot Notation 142
Returning Fields 142 SimplifyingQuerieswithSort, Limit,andSkip 143
Aggregating Queries 145
Specifying
anIndex withHintO • 147Refining Queries with Conditional Operators 148 ConductingSearches with Regular Expression 153
Modifying
the Data 154UpdatingYourData 154
ModifierOperators 156
Saving Documents Quickly withSave() 160
Modifyinga DocumentAtomically 161 Puttingthe Parameters to Work 161
Deleting
Data , 162m CONTENTS
Creating
a Link Between Two Documents 163Retrievingthe Information 165
Summary
166Chapter
8:Creating
aBlog Application
with the PHP Driver... 167Designing
theApplication
168Listing
the Posts 169Paging with PHP andMongoDB 171
Looking
ataSingle
Post 172SpecifyingAdditional Variables 173
Viewingand Adding Comments 174
Searching
the Posts 175Adding, Deleting,
andModifying
Posts 176Adding aNew Post 177
Editinga Post 178
DeletingaPost 179
Creating
the IndexPages
180Recapping
theblog Application
181Summary
190Part III: Advanced 191
Chapter
9: Database Administration 193Using
AdministrativeTools 194mongo, the MongoDB Console 194
UsingThird-PartyAdministrationTools 194
Backing
up theMongoDB
Server 194Creating aBackup101 194
Backing up aSingleDatabase 197
Backing up aSingleCollection 197
Digging
Deeper
intoBackups
197Restoring
Individual Databases or Collections 198RestoringaSingleDatabase • 199
Restoring aSingleCollection 199
Automating Backups
199UsingaLocal Datastore 199
Using aRemote(Cloud-Based) Datastore 202
Backing
upLarge
Databases 203UsingaSlave ServerforBackups • 203
Creating Snapshots withaJournaling Filesystem 203
DiskLayoutto Use with VolumeManagers 205
Importing
Data intoMongoDB
206Exporting
Data fromMongoDB
207Securing
Your Data 208RestrictingAccess toa MongoDB Server 208
Protecting
Your Server withAuthentication 208AddinganAdmin User 209
Enabling Authentication 209 Authenticatingin the mongo Console 209 ChangingaUser's Credentials 210 Adding aRead-Only User 211
DeletingaUser 211
UsingAuthenticated Connections in aPHPApplication 212
Managing
Servers 212StartingaServer 212
Reconfiguring
aServer 213Gettingthe Server's Version 214
Gettingthe Server's Status 214
ShuttingDowna Server 216
Using
MongoDB Logfiles
217Validating
andRepairing
Your Data , 217RepairingaServer , ,„„. 217
aCONTENTS
ValidatingaSingleCollection 218
RepairingCollection ValidationFaults 219 RepairingaCollection's Datafiles 220
Upgrading MongoDB
221Monitoring MongoDB
221RollingYourOwn Stat Monitoring Tool 222
Using
themongod
Web Interface 223Summary
223Chapter
10:Optimization
225Optimizing
Your Server Hardware for Performance 225UnderstandingHowMongoDB UsesMemory 225
ChoosingtheRightDatabase Server Hardware 226
Evaluating Query
Performance 226MongoDB
Profiler 226Enabling andDisablingthe DBProfiler 227 AnalyzingaSpecific Querywith explainO 228
UsingProfile andexplainO toOptimizeaQuery 229
Managing
Indexes 232ListingIndexes 233
CreatingaSimple Index 233
Creating aCompound Index 234
Specifying
IndexOptions
235 Creatingan Index in the Backgroundwith{background:true} 235CreatinganIndexwith aUnique Key {unique:true} 236
Dropping Duplicates Automaticallywith{dropdups:true} 236
Dropping an Index 236
Re-IndexingaCollection 237
How
MongoDB
SelectsWhich Indexes It Will Use 237Using
HintQ
to ForceUsing
aSpecific
Index 238Optimizing
theStorage
of SmallObjects
238Summary
• 239Chapter
11:Replication
• »241Spelling
OutMongoDB's
Replication
Goals 242ImprovingScalability 242 Improving Durability/Reliability 242
ProvidingIsolation 243
Drilling
Down ontheOplog
...243Implementing Single
Master/Single
SlaveReplication
244Setting Up aMaster/SlaveReplication Configuration 245
Implementing Single Master/Multiple
SlaveReplication
248Configuring
a Master/SlaveReplication System
248Resynchronizing
aMaster/SlaveReplication System
....249Issuing aManualResyncCommand tothe Slave 250
Resyncing byDeletingtheSlaves Datafiles 250 ResyncingaSlavewiththe --fastsync Option 250
Implementing
Multiple Master/Single
SlaveReplication
.251Setting upaMultipleMaster/Slave Replication Configuration 251
Exploring
VariousReplication
Scenarios ....254ImplementingCascadeReplication 254 ImplementingMaster/MasterReplication 254 ImplementingInterleaved Replication 255
Using
Replica
Pairs 256ResolvingServerDisputeswith anArbiter 261
Implementing
AdvancedClustering
withReplica
Sets 262Creating aReplicaSet 264
GettingaReplicaSet MemberUpandRunning 265
Adding aServertoaReplica Set ...266
Managing ReplicaSets , ., ,..,267
CONTENTS
ConfiguringtheOptionsforReplicaSet Members 271 DeterminingtheStatusofReplicaSets 273 ConnectingtoaReplicaSetfrom YourApplication 273
Summary
275Chapter
12:Sharding
277Exploring
the Need forSharding
277Partitioning
Horizontal andVertical Data 278PartitioningDataVertically 278
PartitioningData Horizontally 278
Analyzing
aSimple
Sharding
Scenario 279Implementing
Sharding
withMongoDB
280Setting Up
aSharding
Configuration
282AddingaNew Shard to the Cluster 285
Removing
aShard fromthe Cluster 287Determining
HowYou're Connected 288Listing
the Status ofaSharded Cluster 288Using
Replica
SetstoImplement Shards 290Sharding
toImprove
Performance 290Summary
291tIndex 293