Σχόλια 0

Το κείμενο του εγγράφου

MongoDB DocumentationRelease 2.4.8MongoDB Documentation ProjectNovember 26,20132Contents1 Install MongoDB 31.1 Installation Guides............................................31.2 First Steps with MongoDB........................................192 MongoDB CRUD Operations 272.1 MongoDB CRUD Introduction.....................................272.2 MongoDB CRUD Concepts.......................................292.3 MongoDB CRUD Tutorials.......................................582.4 MongoDB CRUD Reference.......................................823 Data Models 973.1 Data Modeling Introduction.......................................973.2 Data Modeling Concepts.........................................993.3 Data Model Examples and Patterns...................................1063.4 Data Model Reference..........................................1214 Administration 1354.1 Administration Concepts.........................................1354.2 Administration Tutorials.........................................1694.3 Administration Reference........................................2245 Security 2375.1 Security Introduction...........................................2375.2 Security Concepts............................................2395.3 Security Tutorials.............................................2455.4 Security Reference............................................2676 Aggregation 2776.1 Aggregation Introduction........................................2776.2 Aggregation Concepts..........................................2816.3 Aggregation Examples..........................................2926.4 Aggregation Reference..........................................3087 Indexes 3137.1 Index Introduction............................................3137.2 Index Concepts..............................................3187.3 Indexing Tutorials............................................3387.4 Indexing Reference............................................37418 Replication 3778.1 Replication Introduction.........................................3778.2 Replication Concepts...........................................3818.3 Replica Set Tutorials...........................................4198.4 Replication Reference..........................................4669 Sharding 4919.1 Sharding Introduction..........................................4919.2 Sharding Concepts............................................4969.3 Sharded Cluster Tutorials........................................5179.4 Sharding Reference...........................................55810 Frequently Asked Questions 57510.1 FAQ:MongoDB Fundamentals.....................................57510.2 FAQ:MongoDB for Application Developers..............................57810.3 FAQ:The mongo Shell.........................................58810.4 FAQ:Concurrency............................................59010.5 FAQ:Sharding with MongoDB.....................................59410.6 FAQ:Replica Sets and Replication in MongoDB............................60010.7 FAQ:MongoDB Storage.........................................60310.8 FAQ:Indexes...............................................60710.9 FAQ:MongoDB Diagnostics.......................................61011 Release Notes 61511.1 Current Stable Release..........................................61511.2 Previous Stable Releases.........................................63311.3 Other MongoDB Release Notes.....................................65811.4 MongoDB Version Numbers.......................................65912 About MongoDB Documentation 66112.1 License..................................................66112.2 Editions..................................................66112.3 Version and Revisions..........................................66212.4 Report an Issue or Make a Change Request...............................66212.5 Contribute to the Documentation....................................662Index 6792MongoDB Documentation,Release 2.4.8See About MongoDB Documentation (page 661) for more information about the MongoDB Documentation project,this Manual and additional editions of this text.Note:This version of the PDF does not include the reference section,see MongoDB Reference Manual1for a PDFedition of all MongoDB Reference Material.1http://docs.mongodb.org/v2.4/MongoDB-reference-manual.pdfContents 1MongoDB Documentation,Release 2.4.82 ContentsCHAPTER 1Install MongoDBMongoDB runs on most platforms and supports both 32-bit and 64-bit architectures.1.1 Installation GuidesSeeRelease Notes (page 615) for information about speciﬁc releases of MongoDB.1.1.1 LinuxInstall on Linux (page 3)Install on LinuxThese documents provide instructions to install MongoDB for various Linux systems.RecommendedFor easy installation,MongoDB provides packages for popular Linux distributions.The following guides detail theinstallation process for these systems:Install on Red Hat Enterprise Linux (page 4) Install MongoDB on Red Hat Enterprise,CentOS,Fedora and relatedLinux systems using.rpm packages.Install on Ubuntu (page 6) Install MongoDB on Ubuntu Linux systems using.deb packages.Install on Debian (page 7) Install MongoDB on Debian systems using.deb packages.For systems without supported packages,refer to the Manual Installation tutorial.Manual InstallationAlthough packages are the preferred installation method,for Linux systems without supported packages,see thefollowing guide:Install on Other Linux Systems (page 9) Install MongoDB on other Linux systems fromthe MongoDB archives.3MongoDB Documentation,Release 2.4.8Install MongoDB on Red Hat Enterprise,CentOS,or Fedora This tutorial outlines the steps to install MongoDBon Red Hat Enterprise Linux,CentOS Linux,Fedora Linux and related systems.The tutorial uses.rpm packages toinstall.While some of these distributions include their own MongoDB packages,the ofﬁcial MongoDB packages aregenerally more up to date.Packages The MongoDB downloads repository contains two packages:• mongo-10gen-serverThis package contains the mongod and mongos daemons from the latest stable release and associated con-ﬁguration and init scripts.Additionally,you can use this package to install daemons from a previous release(page 4) of MongoDB.• mongo-10genThis package contains all MongoDB tools fromthe latest stable release.Additionally,you can use this packageto install tools from a previous release (page 4) of MongoDB.Install this package on all production MongoDBhosts and optionally on other systems fromwhich you may need to administer MongoDB systems.Install MongoDBConﬁgure Package Management System(YUM) Create a/etc/yum.repos.d/mongodb.repo ﬁle to holdthe following conﬁguration information for the MongoDB repository:TipFor production deployments,always run MongoDB on 64-bit systems.If you are running a 64-bit system,use the following conﬁguration:[mongodb]name=MongoDB Repositorybaseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/gpgcheck=0enabled=1If you are running a 32-bit system,which is not recommended for production deployments,use the following conﬁg-uration:[mongodb]name=MongoDB Repositorybaseurl=http://downloads-distro.mongodb.org/repo/redhat/os/i686/gpgcheck=0enabled=1Install Packages Issue the following command (as root or with sudo) to install the latest stable version of Mon-goDB and the associated tools:yum install mongo-10gen mongo-10gen-serverWhen this command completes,you have successfully installed MongoDB!Manage Installed Versions You can use the mongo-10gen and mongo-10gen-server packages to installprevious releases of MongoDB.To install a speciﬁc release,append the version number,as in the following example:4 Chapter 1.Install MongoDBMongoDB Documentation,Release 2.4.8yum install mongo-10gen-2.2.3 mongo-10gen-server-2.2.3This installs the mongo-10gen and mongo-10gen-server packages with the 2.2.3 release.You can specifyany available version of MongoDB;however yum will upgrade the mongo-10gen and mongo-10gen-serverpackages when a newer version becomes available.Use the following pinning procedure to prevent unintended up-grades.To pin a package,add the following line to your/etc/yum.conf ﬁle:exclude=mongo-10gen,mongo-10gen-serverControl ScriptsWarning:With the introduction of systemd in Fedora 15,the control scripts included in the packages availablein the MongoDB downloads repository are not compatible with Fedora systems.A correction is forthcoming,see SERVER-7285afor more information,and in the mean time use your own control scripts or install using theprocedure outlined in Install MongoDB on Linux Systems (page 9).ahttps://jira.mongodb.org/browse/SERVER-7285The packages include various control scripts,including the init script/etc/rc.d/init.d/mongod.These pack-ages conﬁgure MongoDB using the/etc/mongod.conf ﬁle in conjunction with the control scripts.As of version 2.4.8,there are no control scripts for mongos.mongos is only used in sharding deployments(page 496).You can use the mongod init script to derive your own mongos control script.Run MongoDBImportant:You must SELinux to allow MongoDB to start on Fedora systems.Administrators have two options:• enable access to the relevant ports (e.g.27017) for SELinux.See Conﬁguration Options (page 242) for moreinformation on MongoDB’s default ports (page 275).• disable SELinux entirely.This requires a systemreboot and may have larger implications for your deployment.Start MongoDB The MongoDB instance stores its data ﬁles in the/var/lib/mongo and its log ﬁles in/var/log/mongo,and run using the mongod user account.If you change the user that runs the MongoDBprocess,you must modify the access control rights to the/var/lib/mongo and/var/log/mongo directories.Start the mongod process by issuing the following command (as root or with sudo):service mongod startYou can verify that the mongod process has started successfully by checking the contents of the log ﬁle at/var/log/mongo/mongod.log.You may optionally ensure that MongoDB will start following a system reboot by issuing the following command(with root privileges:)chkconfig mongod onStop MongoDB Stop the mongod process by issuing the following command (as root or with sudo):service mongod stop1.1.Installation Guides 5MongoDB Documentation,Release 2.4.8Restart MongoDB You can restart the mongod process by issuing the following command (as root or with sudo):service mongod restartFollow the state of this process by watching the output in the/var/log/mongo/mongod.log ﬁle to watch forerrors or important messages fromthe server.Install MongoDB on Ubuntu This tutorial outlines the steps to install MongoDB on Ubuntu Linux systems.Thetutorial uses.deb packages to install.Although Ubuntu include its own MongoDB packages,the ofﬁcial MongoDBpackages are generally more up to date.Note:If you use an older Ubuntu that does not use Upstart,(i.e.any version before 9.10 “Karmic”) please followtheinstructions on the Install MongoDB on Debian (page 7) tutorial.Package Options The MongoDB downloads repository provides the mongodb-10gen package,which containsthe latest stable release.Additionally you can install previous releases (page 6) of MongoDB.You cannot install this package concurrently with the mongodb,mongodb-server,or mongodb-clientspack-ages provided by Ubuntu.Install MongoDBConﬁgure Package Management System (APT) The Ubuntu package management tool (i.e.dpkg and apt)ensure package consistency and authenticity by requiring that distributors sign packages with GPG keys.Issue thefollowing command to import the MongoDB public GPG Key1:sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10Create a/etc/apt/sources.list.d/mongodb.list ﬁle using the following command.echo'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen'| sudo tee/etc/apt/sources.list.d/mongodb.listNow issue the following command to reload your repository:sudo apt-get updateInstall Packages Issue the following command to install the latest stable version of MongoDB:sudo apt-get install mongodb-10genWhen this command completes,you have successfully installed MongoDB!Continue for conﬁguration and start-upsuggestions.Manage Installed Versions You can use the mongodb-10gen package to install previous versions of MongoDB.To install a speciﬁc release,append the version number to the package name,as in the following example:apt-get install mongodb-10gen=2.2.3This will install the 2.2.3 release of MongoDB.You can specify any available version of MongoDB;howeverapt-get will upgrade the mongodb-10gen package when a newer version becomes available.Use the followingpinning procedure to prevent unintended upgrades.1http://docs.mongodb.org/10gen-gpg-key.asc6 Chapter 1.Install MongoDBMongoDB Documentation,Release 2.4.8To pin a package,issue the following command at the system prompt to pin the version of MongoDB at the currentlyinstalled version:echo"mongodb-10gen hold"| sudo dpkg --set-selectionsControl Scripts The packages include various control scripts,including the init script/etc/rc.d/init.d/mongod.These packages conﬁgure MongoDB using the/etc/mongod.conf ﬁlein conjunction with the control scripts.As of version 2.4.8,there are no control scripts for mongos.mongos is only used in sharding deployments(page 496).You can use the mongod init script to derive your own mongos control script.Run MongoDB The MongoDB instance stores its data ﬁles in the/var/lib/mongo and its log ﬁles in/var/log/mongo,and run using the mongod user account.If you change the user that runs the MongoDBprocess,you must modify the access control rights to the/var/lib/mongo and/var/log/mongo directories.Start MongoDB You can start the mongod process by issuing the following command:sudo service mongodb startYou can verify that mongod has started successfully by checking the contents of the log ﬁle at/var/log/mongodb/mongodb.log.Stop MongoDB As needed,you may stop the mongod process by issuing the following command:sudo service mongodb stopRestart MongoDB You may restart the mongod process by issuing the following command:sudo service mongodb restartInstall MongoDB on Debian This tutorial outlines the steps to install MongoDB on Debian systems.The tutorialuses.deb packages to install.While some Debian distributions include their own MongoDB packages,the ofﬁcialMongoDB packages are generally more up to date.Note:This tutorial applies to both Debian systems and versions of Ubuntu Linux prior to 9.10 “Karmic” which donot use Upstart.Other Ubuntu users will want to follow the Install MongoDB on Ubuntu (page 6) tutorial.Package Options The downloads repository provides the mongodb-10gen package,which contains the lateststable release.Additionally you can install previous releases (page 8) of MongoDB.You cannot install this package concurrently with the mongodb,mongodb-server,or mongodb-clientspack-ages that your release of Debian may include.Install MongoDBConﬁgure Package Management System (APT) The Debian package management tools (i.e.dpkg and apt)ensure package consistency and authenticity by requiring that distributors sign packages with GPG keys.1.1.Installation Guides 7MongoDB Documentation,Release 2.4.8Step 1:Import MongoDB PGP Key Issue the following command to add the MongoDB public GPG Key2to thesystemkey ring.sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10Step 2:Create a sources.listﬁle for MongoDB Create a/etc/apt/sources.list.d/mongodb.listﬁleecho'deb http://downloads-distro.mongodb.org/repo/debian-sysvinit dist 10gen'| sudo tee/etc/apt/sources.list.d/mongodb.listStep 3:Reload Local Package Database Issue the following command to reload the local package database:sudo apt-get updateInstall Packages Issue the following command to install the latest stable version of MongoDB:sudo apt-get install mongodb-10genWhen this command completes,you have successfully installed MongoDB!Manage Installed Versions You can use the mongodb-10gen package to install previous versions of MongoDB.To install a speciﬁc release,append the version number to the package name,as in the following example:apt-get install mongodb-10gen=2.2.3This will install the 2.2.3 release of MongoDB.You can specify any available version of MongoDB;howeverapt-get will upgrade the mongodb-10gen package when a newer version becomes available.Use the followingpinning procedure to prevent unintended upgrades.To pin a package,issue the following command at the system prompt to pin the version of MongoDB at the currentlyinstalled version:echo"mongodb-10gen hold"| sudo dpkg --set-selectionsControl Scripts The packages include various control scripts,including the init script/etc/rc.d/init.d/mongod.These packages conﬁgure MongoDB using the/etc/mongod.conf ﬁlein conjunction with the control scripts.As of version 2.4.8,there are no control scripts for mongos.mongos is only used in sharding deployments(page 496).You can use the mongod init script to derive your own mongos control script.Run MongoDB The MongoDB instance stores its data ﬁles in the/var/lib/mongo and its log ﬁles in/var/log/mongo,and run using the mongod user account.If you change the user that runs the MongoDBprocess,you must modify the access control rights to the/var/lib/mongo and/var/log/mongo directories.Start MongoDB Issue the following command to start mongod:sudo/etc/init.d/mongodb startYou can verify that mongod has started successfully by checking the contents of the log ﬁle at/var/log/mongodb/mongodb.log.2http://docs.mongodb.org/10gen-gpg-key.asc8 Chapter 1.Install MongoDBMongoDB Documentation,Release 2.4.8Stop MongoDB Issue the following command to stop mongod:sudo/etc/init.d/mongodb stopRestart MongoDB Issue the following command to restart mongod:sudo/etc/init.d/mongodb restartInstall MongoDB on Linux Systems Compiled versions of MongoDB for Linux provide a simple option for in-stalling MongoDB for other Linux systems without supported packages.Installation Process MongoDBprovides archives for both 64-bit and 32-bit Linux.Followthe installation procedureappropriate for your system.Install for 64-bit LinuxStep 1:Download the Latest Release In a systemshell,download the latest release for 64-bit Linux.curl -O http://downloads.mongodb.org/linux/mongodb-linux-x86_64-2.5.4.tgzYou may optionally specify a different version to download.Step 2:Extract MongoDB FromArchive Extract the ﬁles fromthe downloaded archive.tar -zxvf mongodb-linux-x86_64-2.5.4.tgzStep 3:Optional.Copy MongoDB to Target Directory Copy the extracted folder into another location,such asmongodb.mkdir -p mongodbcp -R -n mongodb-linux-x86_64-2.5.4/mongodbStep 4:Optional.Conﬁgure Search Path To ensure that the downloaded binaries are in your PATH,you canmodify your PATH and/or create symbolic links to the MongoDB binaries in your/usr/local/bin directory(/usr/local/bin is already in your PATH).You can ﬁnd the MongoDB binaries in the bin/directory within thearchive.Install for 32-bit LinuxStep 1:Download the Latest Release In a systemshell,download the latest release for 32-bit Linux.curl -O http://downloads.mongodb.org/linux/mongodb-linux-i686-2.5.4.tgzYou may optionally specify a different version to download.Step 2:Extract MongoDB FromArchive Extract the ﬁles fromthe downloaded archive.1.1.Installation Guides 9MongoDB Documentation,Release 2.4.8tar -zxvf mongodb-linux-i686-2.5.4.tgzStep 3:Optional.Copy MongoDB to Target Directory Copy the extracted folder into another location,such asmongodb.mkdir -p mongodbcp -R -n mongodb-linux-i686-2.5.4/mongodbStep 4:Optional.Conﬁgure Search Path To ensure that the downloaded binaries are in your PATH,you canmodify your PATH and/or create symbolic links to the MongoDB binaries in your/usr/local/bin directory(/usr/local/bin is already in your PATH).You can ﬁnd the MongoDB binaries in the bin/directory within thearchive.Run MongoDBSet Up the Data Directory Before you start mongod for the ﬁrst time,you will need to create the data directory(i.e.dbpath).By default,mongod writes data to the/data/db directory.Step 1:Create dbpath To create the default dbpath directory,use the following command:mkdir -p/data/dbStep 2:Set dbpath Permissions Ensure that the user that runs the mongod process has read and write permissionsto this directory.For example,if you will run the mongod process,change the owner of the/data/db directory:chown mongodb/data/dbYou must create the mongodb user separately.You can specify an alternate path for data ﬁles using the --dbpath option to mongod.If you use an alternatelocation for your data directory,ensure that this user can write to the alternate data directory.Start MongoDB To start mongod,run the executable mongod at the systemprompt.For example,if your PATH includes the location of the mongod binary,enter mongod at the systemprompt.mongodIf your PATH does not include the location of the mongod binary,enter the full path to the mongod binary.Starting mongod without any arguments starts a MongoDB instance that writes data to the/data/db directory.Tospecify an alternate data directory,start mongod with the --dbpath option:mongod --dbpath <some alternate directory>Whether using the default/data/db or an alternate directory,ensure that the user account running mongod has readand write permissions to the directory.Stop MongoDB To stop the mongod instance,press Control+C in the terminal where the mongod instance isrunning.10 Chapter 1.Install MongoDBMongoDB Documentation,Release 2.4.81.1.2 OS XInstall MongoDB on OS X (page 11)Install MongoDB on OS XPlatformSupportStarting in version 2.4,MongoDB only supports OS X versions 10.6 (Snow Leopard) on Intel x86-64 and later.MongoDB is available through the popular OS X package manager Homebrew3or through the MongoDB Downloadsite.Install MongoDB with HomebrewHomebrew4 5installs binary packages based on published “formulae”.The following commands will update brew tothe latest packages and install MongoDB.In a terminal shell,use the following sequence of commands to update‘‘brew‘‘ to the latest packages and installMongoDB:brew updatebrew install mongodbLater,if you need to upgrade MongoDB,run the following sequence of commands to update the MongoDBinstallationon your system:brew updatebrew upgrade mongodbManual InstallationStep 1:Download the Latest Release In a systemshell,download the latest release for 64-bit OS X.curl -O http://downloads.mongodb.org/osx/mongodb-osx-x86_64-2.5.4.tgzYou may optionally specify a different version to download.Step 2:Extract MongoDB FromArchive Extract the ﬁles fromthe downloaded archive.tar -zxvf mongodb-osx-x86_64-2.5.4.tgzStep 3:Optional.Copy MongoDB to Target Directory Copy the extracted folder into another location,such asmongodb.mkdir -p mongodbcp -R -n mongodb-osx-x86_64-2.5.4/mongodb3http://mxcl.github.com/homebrew/4http://brew.sh/5Homebrew requires some initial setup and conﬁguration.This conﬁguration is beyond the scope of this document.1.1.Installation Guides 11MongoDB Documentation,Release 2.4.8Step 4:Optional.Conﬁgure Search Path To ensure that the downloaded binaries are in your PATH,you canmodify your PATH and/or create symbolic links to the MongoDB binaries in your/usr/local/bin directory(/usr/local/bin is already in your PATH).You can ﬁnd the MongoDB binaries in the bin/directory within thearchive.Run MongoDBSet Up the Data Directory Before you start mongod for the ﬁrst time,you will need to create the data directory.By default,mongod writes data to the/data/db/directory.Step 1:Create dbpath To create the default dbpath directory,use the following command:mkdir -p/data/dbStep 2:Set dbpath Permissions Ensure that the user that runs the mongod process has read and write permissionsto this directory.For example,if you will run the mongod process,change the owner of the/data/db directory:chown`id -u`/data/dbYou must create the mongodb user separately.You can specify an alternate path for data ﬁles using the --dbpath option to mongod.If you use an alternatelocation for your data directory,ensure that the alternate directory has the appropriate permissions.Start MongoDB To start mongod,run the executable mongod at the systemprompt.For example,if your PATH includes the location of the mongod binary,enter mongod at the systemprompt.mongodIf your PATH does not include the location of the mongod binary,enter the full path to the mongod binary.The previous command starts a mongod instance that writes data to the/data/db/directory.To specify an alternatedata directory,start mongod with the --dbpath option:mongod --dbpath <some alternate directory>Whether using the default/data/db/or an alternate directory,ensure that the user account running mongod hasread and write permissions to the directory.Stop MongoDB To stop the mongod instance,press Control+C in the terminal where the mongod instance isrunning.1.1.3 WindowsInstall MongoDB on Windows (page 12)Install MongoDB on WindowsPlatformSupportStarting in version 2.2,MongoDB does not support Windows XP.Please use a more recent version of Windows to usemore recent releases of MongoDB.12 Chapter 1.Install MongoDBMongoDB Documentation,Release 2.4.8Important:If you are running any edition of Windows Server 2008 R2 or Windows 7,please install a hotﬁx toresolve an issue with memory mapped ﬁles on Windows6.Download MongoDB for WindowsThere are three builds of MongoDB for Windows:• MongoDBfor Windows Server 2008 R2 edition (i.e.2008R2) only runs on Windows Server 2008 R2,Windows7 64-bit,and newer versions of Windows.This build takes advantage of recent enhancements to the WindowsPlatformand cannot operate on older versions of Windows.• MongoDB for Windows 64-bit runs on any 64-bit version of Windows newer than Windows XP,includingWindows Server 2008 R2 and Windows 7 64-bit.• MongoDB for Windows 32-bit runs on any 32-bit version of Windows newer than Windows XP.32-bit versionsof MongoDBare only intended for older systems and for use in testing and development systems.32-bit versionsof MongoDB only support databases smaller than 2GB.TipTo ﬁnd which version of Windows you are running,enter the following command in the Command Prompt:wmic os get osarchitecture1.Download the latest production release of MongoDB fromthe MongoDB downloads page7.Ensure you down-load the correct version of MongoDB for your Windows system.The 64-bit versions of MongoDB will notwork with 32-bit Windows.2.Extract the downloaded archive.(a) In Windows Explorer,ﬁnd the MongoDB download ﬁle,typically in the default Downloads directory.(b) Extract the archive to C:\by right clicking on the archive and selecting Extract All and browsing to C:\.3.Optional.Move the MongoDB directory to another location.For example,to move the directory toC:\mongodb directory:(a) Go Start Menu > All Programs > Accessories.(b) Right click Command Prompt,and select Run as Administrator fromthe popup menu.(c) In the Command Prompt,issue the following commands:cd\move C:\mongodb-win32-*C:\mongodbNote:MongoDB is self-contained and does not have any other system dependencies.You can run MongoDB fromany folder you choose.You may install MongoDB in any directory (e.g.D:\test\mongodb)Run MongoDB6http://support.microsoft.com/kb/27312847http://www.mongodb.org/downloads1.1.Installation Guides 13MongoDB Documentation,Release 2.4.8Set Up the Data Directory MongoDBrequires a data folder to store its ﬁles.The default location for the MongoDBdata directory is C:\data\db.Create this folder using the Command Prompt.Go to the C:\directory and issue thefollowing command sequence:md datamd data\dbYou can specify an alternate path for data ﬁles using the --dbpath option to mongod.exe.Start MongoDB To start MongoDB,execute fromthe Command Prompt:C:\mongodb\bin\mongod.exeThis will start the main MongoDB database process.The waiting for connections message in the consoleoutput indicates that the mongod.exe process is running successfully.Note:Depending on the security level of your system,Windows will issue a Security Alert dialog box about blocking“some features” of C:\\mongodb\bin\mongod.exe from communicating on networks.All users should selectPrivate Networks,such as my home or work network and click Allow access.For additionalinformation on security and MongoDB,please read the Security Concepts (page 239) page.Warning:Do not allowmongod.exe to be accessible to public networks without running in “Secure Mode” (i.e.auth.) MongoDB is designed to be run in “trusted environments” and the database does not enable authenticationor “Secure Mode” by default.You may specify an alternate path for\data\db with the dbpath setting for mongod.exe,as in the followingexample:C:\mongodb\bin\mongod.exe --dbpath d:\test\mongodb\dataIf your path includes spaces,enclose the entire path in double quotations,for example:C:\mongodb\bin\mongod.exe --dbpath"d:\test\mongo db data"Connect to MongoDB Connect to MongoDB using the mongo.exe shell.Open another Command Prompt andissue the following command:C:\mongodb\bin\mongo.exeNote:Executing the command start C:\mongodb\bin\mongo.exewill automatically start the mongo.exeshell in a separate Command Prompt window.The mongo.exe shell will connect to mongod.exe running on the localhost interface and port 27017 by default.At the mongo.exe prompt,issue the following two commands to insert a record in the test collection of the defaulttest database and then retrieve that record:db.test.save( { a:1 } )db.test.find()See also:mongo and http://docs.mongodb.org/manualreference/method.If you want to develop applicationsusing.NET,see the documentation of C#and MongoDB8for more information.8http://docs.mongodb.org/ecosystem/drivers/csharp14 Chapter 1.Install MongoDBMongoDB Documentation,Release 2.4.8MongoDB as a Windows ServiceNew in version 2.0.You can set up MongoDB as a Windows Service so that the database will start automatically following each rebootcycle.Note:mongod.exe added support for running as a Windows service in version 2.0,and mongos.exe addedsupport for running as a Windows Service in version 2.1.1.Conﬁgure the System The following steps,although optional,are good practice.You should specify two options when running MongoDB as a Windows Service:a path for the log output (i.e.logpath) and a configuration file.1.Optional.Create a speciﬁc directory for MongoDB log ﬁles:md C:\mongodb\log2.Optional.Create a conﬁguration ﬁle for the logpath option for MongoDBin the Command Prompt by issuingthis command:echo logpath=C:\mongodb\log\mongo.log > C:\mongodb\mongod.cfgNote:Consider setting the logappend option.If you do not,mongod.exe will delete the contents of the existinglog ﬁle when starting.Changed in version 2.2:The default logpath and logappend behavior changed in the 2.2 release.Install and Run the MongoDB Service Run all of the following commands in Command Prompt with “Adminis-trative Privileges:”1.To install the MongoDB service:C:\mongodb\bin\mongod.exe --config C:\mongodb\mongod.cfg --installModify the path to the mongod.cfg ﬁle as needed.For the --install option to succeed,you must specifya logpath setting or the --logpath run-time option.2.To run the MongoDB service:net start MongoDBIf you wish to use an alternate path for your dbpath specify it in the conﬁg ﬁle (e.g.C:\mongodb\mongod.cfg)on that you speciﬁed in the --install operation.You may also specify --dbpath on the command line;however,always prefer the conﬁguration ﬁle.If you have not set up the data directory,set up the data directory (page 13) where MongoDB will store its data ﬁles.If the dbpath directory does not exist,mongod.exe will not be able to start.The default value for dbpath is\data\db.Stop or Remove the MongoDB Service To stop the MongoDB service:net stop MongoDBTo remove the MongoDB service:1.1.Installation Guides 15MongoDB Documentation,Release 2.4.8C:\mongodb\bin\mongod.exe --remove1.1.4 MongoDB EnterpriseInstall MongoDB Enterprise (page 16)Install MongoDB EnterpriseNew in version 2.2.MongoDB Enterprise9is available on four platforms and contains support for several features related to security andmonitoring.Required PackagesChanged in version 2.4.4:MongoDB Enterprise uses Cyrus SASL instead of GNU SASL.Earlier 2.4 Enterpriseversions use GNU SASL (libgsasl) instead.For required packages for the earlier 2.4 versions,see Earlier 2.4Versions (page 16).To use MongoDB Enterprise,you must install several prerequisites.The names of the packages vary by distributionand are as follows:• Debian or Ubuntu 12.04 require:libssl0.9.8,snmp,snmpd,cyrus-sasl2-dbg,cyrus-sasl2-mit-dbg,libsasl2-2,libsasl2-dev,libsasl2-modules,andlibsasl2-modules-gssapi-mit.Issue a command such as the following to install these pack-ages:sudo apt-get install libssl0.9.8 snmp snmpd cyrus-sasl2-dbg cyrus-sasl2-mit-dbg libsasl2-2 libsasl2-dev libsasl2-modules libsasl2-modules-gssapi-mit• CentOS and Red Hat Enterprise Linux 6.x and 5.x,as well as Amazon Linux AMI require:net-snmp,net-snmp-libs,openssl,net-snmp-utils,cyrus-sasl,cyrus-sasl-lib,cyrus-sasl-devel,and cyrus-sasl-gssapi.Issue a command such as the following to install thesepackages:sudo yum install openssl net-snmp net-snmp-libs net-snmp-utils cyrus-sasl cyrus-sasl-lib cyrus-sasl-devel cyrus-sasl-gssapi• SUSE Enterprise Linux requires libopenssl0_9_8,libsnmp15,slessp1-libsnmp15,snmp-mibs,cyrus-sasl,cyrus-sasl-devel,and cyrus-sasl-gssapi.Issue a commandsuch as the following to install these packages:sudo zypper install libopenssl0_9_8 libsnmp15 slessp1-libsnmp15 snmp-mibs cyrus-sasl cyrus-sasl-devel cyrus-sasl-gssapiEarlier 2.4 Versions Before version 2.4.4,the 2.4 versions of MongoDB Enterprise use libgsasl10.The requiredpackages for the different distributions are as follows:• Ubuntu 12.04 requires libssl0.9.8,libgsasl,snmp,and snmpd.Issue a command such as the follow-ing to install these packages:sudo apt-get install libssl0.9.8 libgsasl7 snmp snmpd9http://www.mongodb.com/products/mongodb-enterprise10http://www.gnu.org/software/gsasl/16 Chapter 1.Install MongoDBMongoDB Documentation,Release 2.4.8• Red Hat Enterprise Linux 6.x series and Amazon Linux AMI require openssl,libgsasl7,net-snmp,net-snmp-libs,and net-snmp-utils.To download libgsasl you must enable the EPEL repositoryby issuing the following sequence of commands to add and update the systemrepositories:sudo rpm -ivh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpmsudo yum update -yWhen you have installed and updated the EPEL repositories,issue the following install these packages:sudo yum install openssl net-snmp net-snmp-libs net-snmp-utils libgsasl• SUSE Enterprise Linux requires libopenssl0_9_8,libsnmp15,slessp1-libsnmp15,andsnmp-mibs.Issue a command such as the following to install these packages:sudo zypper install libopenssl0_9_8 libsnmp15 slessp1-libsnmp15 snmp-mibsNote:Before 2.4.4,MongoDB Enterprise 2.4 for SUSE requires libgsasl11which is not available in the defaultrepositories for SUSE.Install MongoDB Enterprise BinariesWhen you have installed the required packages,and downloaded the Enterprise packages12you can install the packagesusing the same procedure as a standard installation of MongoDB on Linux Systems (page 9).Note:.deb and.rpm packages for Enterprise releases are available for some platforms.You can use these to installMongoDB directly using the dpkg and rpm utilities.Use the sequence of commands below to download and extract MongoDB Enterprise packages appropriate for yourdistribution:Ubuntu 12.04curl -O http://downloads.10gen.com/linux/mongodb-linux-x86_64-subscription-ubuntu1204-2.5.4.tgztar -zxvf mongodb-linux-x86_64-subscription-ubuntu1204-2.5.4.tgzcp -R -n mongodb-linux-x86_64-subscription-ubuntu1204-2.5.4/mongodbRed Hat Enterprise Linux 6.xcurl -O http://downloads.10gen.com/linux/mongodb-linux-x86_64-subscription-rhel62-2.5.4.tgztar -zxvf mongodb-linux-x86_64-subscription-rhel62-2.5.4.tgzcp -R -n mongodb-linux-x86_64-subscription-rhel62-2.5.4/mongodbAmazon Linux AMIcurl -O http://downloads.10gen.com/linux/mongodb-linux-x86_64-subscription-amzn64-2.5.4.tgztar -zxvf mongodb-linux-x86_64-subscription-amzn64-2.5.4.tgzcp -R -n mongodb-linux-x86_64-subscription-amzn64-2.5.4/mongodb11http://www.gnu.org/software/gsasl/12http://www.mongodb.com/products/mongodb-enterprise1.1.Installation Guides 17MongoDB Documentation,Release 2.4.8SUSE Enterprise Linuxcurl -O http://downloads.10gen.com/linux/mongodb-linux-x86_64-subscription-suse11-2.5.4.tgztar -zxvf mongodb-linux-x86_64-subscription-suse11-2.5.4.tgzcp -R -n mongodb-linux-x86_64-subscription-suse11-2.5.4/mongodbRunning and Using MongoDBNote:The Enterprise packages currently include an example SNMP conﬁguration ﬁle named mongod.conf.Thisﬁle is not a MongoDB conﬁguration ﬁle.Before you start mongod for the ﬁrst time,you will need to create the data directory (i.e.dbpath).By default,mongod writes data to the/data/db directory.Step 1:Create dbpath To create the default dbpath directory,use the following command:mkdir -p/data/dbStep 2:Set dbpath Permissions Ensure that the user that runs the mongod process has read and write permissionsto this directory.For example,if you will run the mongod process,change the owner of the/data/db directory:chown mongodb/data/dbYou must create the mongodb user separately.You can specify an alternate path for data ﬁles using the --dbpath option to mongod.If you use an alternatelocation for your data directory,ensure that this user can write to the alternate data directory.Start MongoDB To start mongod,run the executable mongod at the systemprompt.For example,if your PATH includes the location of the mongod binary,enter mongod at the systemprompt.mongodIf your PATH does not include the location of the mongod binary,enter the full path to the mongod binary.Starting mongod without any arguments starts a MongoDB instance that writes data to the/data/db directory.Tospecify an alternate data directory,start mongod with the --dbpath option:mongod --dbpath <some alternate directory>Whether using the default/data/db or an alternate directory,ensure that the user account running mongod has readand write permissions to the directory.Stop MongoDB To stop the mongod instance,press Control+C in the terminal where the mongod instance isrunning.Further ReadingAs you begin to use MongoDB,consider the Getting Started with MongoDB (page 19) and MongoDB Tutorials(page 186) resources.To read about features only available in MongoDB Enterprise,consider:Monitor MongoDBwith SNMP (page 176) and Deploy MongoDB with Kerberos Authentication (page 261).18 Chapter 1.Install MongoDBMongoDB Documentation,Release 2.4.81.2 First Steps with MongoDBAfter you have installed MongoDB,consider the following documents as you begin to learn about MongoDB:Getting Started with MongoDB (page 19) An introduction to the basic operation and use of MongoDB.Generate Test Data (page 23) To support initial exploration,generate test data to facilitate testing.1.2.1 Getting Started with MongoDBThis tutorial addresses the following aspects of MongoDB use:• Connect to a Database (page 19)– Connect to a mongod (page 19)– Select a Database (page 20)– Display mongo Help (page 20)• Create a Collection and Insert Documents (page 20)• Insert Documents using a For Loop or a JavaScript Function (page 21)• Working with the Cursor (page 21)– Iterate over the Cursor with a Loop (page 21)– Use Array Operations with the Cursor (page 22)– Query for Speciﬁc Documents (page 22)– Return a Single Document froma Collection (page 23)– Limit the Number of Documents in the Result Set (page 23)• Next Steps with MongoDB (page 23)This tutorial provides an introduction to basic database operations using the mongo shell.mongo is a part of thestandard MongoDB distribution and provides a full JavaScript environment with a complete access to the JavaScriptlanguage and all standard functions as well as a full database interface for MongoDB.See the mongo JavaScript API13documentation and the mongo shell JavaScript Method Reference.The tutorial assumes that you’re running MongoDB on a Linux or OS Xoperating systemand that you have a runningdatabase server;MongoDB does support Windows and provides a Windows distribution with identical operation.For instructions on installing MongoDB and starting the database server,see the appropriate installation (page 3)document.Connect to a DatabaseIn this section,you connect to the database server,which runs as mongod,and begin using the mongo shell to selecta logical database within the database instance and access the help text in the mongo shell.Connect to a mongodFroma systemprompt,start mongo by issuing the mongo command,as follows:mongoBy default,mongo looks for a database server listening on port 27017 on the localhost interface.To connect toa server on a different port or interface,use the --port and --host options.13http://api.mongodb.org/js1.2.First Steps with MongoDB 19MongoDB Documentation,Release 2.4.8Select a DatabaseAfter starting the mongo shell your session will use the test database by default.At any time,issue the followingoperation at the mongo to report the name of the current database:db1.Fromthe mongo shell,display the list of databases,with the following operation:show dbs2.Switch to a new database named mydb,with the following operation:use mydb3.Conﬁrm that your session has the mydb database as context,by checking the value of the db object,whichreturns the name of the current database,as follows:dbAt this point,if you issue the show dbs operation again,it will not include the mydb database.MongoDBwill not permanently create a database until you insert data into that database.The Create a Collection andInsert Documents (page 20) section describes the process for inserting data.New in version 2.4:show databases also returns a list of databases.Display mongo HelpAt any point,you can access help for the mongo shell using the following operation:helpFurthermore,you can append the.help() method to some JavaScript methods,any cursor object,as well as the dband db.collection objects to return additional help information.Create a Collection and Insert DocumentsIn this section,you insert documents into a newcollection named testData within the new database named mydb.MongoDB will create a collection implicitly upon its ﬁrst use.You do not need to create a collection before insertingdata.Furthermore,because MongoDB uses dynamic schemas (page 576),you also need not specify the structure ofyour documents before inserting theminto the collection.1.Fromthe mongo shell,conﬁrmyou are in the mydb database by issuing the following:db2.If mongo does not return mydb for the previous operation,set the context to the mydb database,with thefollowing operation:use mydb3.Create two documents named j and k by using the following sequence of JavaScript operations:j = { name:"mongo"}k = { x:3 }4.Insert the j and k documents into the testData collection with the following sequence of operations:20 Chapter 1.Install MongoDBMongoDB Documentation,Release 2.4.8db.testData.insert( j )db.testData.insert( k )When you insert the ﬁrst document,the mongod will create both the mydb database and the testDatacollection.5.Conﬁrmthat the testData collection exists.Issue the following operation:show collectionsThe mongo shell will return the list of the collections in the current (i.e.mydb) database.At this point,the onlycollection is testData.All mongod databases also have a system.indexes (page 228) collection.6.Conﬁrm that the documents exist in the testData collection by issuing a query on the collection using thefind() method:db.testData.find()This operation returns the following results.The ObjectId (page 129) values will be unique:{"_id":ObjectId("4c2209f9f3924d31102bd84a"),"name":"mongo"}{"_id":ObjectId("4c2209fef3924d31102bd84b"),"x":3 }All MongoDB documents must have an _id ﬁeld with a unique value.These operations do not explicitlyspecify a value for the _id ﬁeld,so mongo creates a unique ObjectId (page 129) value for the ﬁeld beforeinserting it into the collection.Insert Documents using a For Loop or a JavaScript FunctionTo perform the remaining procedures in this tutorial,ﬁrst add more documents to your database using one or both ofthe procedures described in Generate Test Data (page 23).Working with the CursorWhen you query a collection,MongoDB returns a “cursor” object that contains the results of the query.The mongoshell then iterates over the cursor to display the results.Rather than returning all results at once,the shell iterates overthe cursor 20 times to display the ﬁrst 20 results and then waits for a request to iterate over the remaining results.Inthe shell,use enter it to iterate over the next set of results.The procedures in this section show other ways to work with a cursor.For comprehensive documentation on cursors,see crud-read-cursor.Iterate over the Cursor with a LoopBefore using this procedure,make sure to add at least 25 documents to a collection using one of the procedures inGenerate Test Data (page 23).You can name your database and collections anything you choose,but this procedurewill assume the database named test and a collection named testData.1.In the MongoDB JavaScript shell,query the testData collection and assign the resulting cursor object to thec variable:var c = db.testData.find()2.Print the full result set by using a while loop to iterate over the c variable:1.2.First Steps with MongoDB 21MongoDB Documentation,Release 2.4.8while ( c.hasNext() ) printjson( c.next() )The hasNext() function returns true if the cursor has documents.The next() method returns the nextdocument.The printjson() method renders the document in a JSON-like format.The operation displays 20 documents.For example,if the documents have a single ﬁeld named x,the operationdisplays the ﬁeld as well as each document’s ObjectId:{"_id":ObjectId("51a7dc7b2cacf40b79990be6"),"x":1 }{"_id":ObjectId("51a7dc7b2cacf40b79990be7"),"x":2 }{"_id":ObjectId("51a7dc7b2cacf40b79990be8"),"x":3 }{"_id":ObjectId("51a7dc7b2cacf40b79990be9"),"x":4 }{"_id":ObjectId("51a7dc7b2cacf40b79990bea"),"x":5 }{"_id":ObjectId("51a7dc7b2cacf40b79990beb"),"x":6 }{"_id":ObjectId("51a7dc7b2cacf40b79990bec"),"x":7 }{"_id":ObjectId("51a7dc7b2cacf40b79990bed"),"x":8 }{"_id":ObjectId("51a7dc7b2cacf40b79990bee"),"x":9 }{"_id":ObjectId("51a7dc7b2cacf40b79990bef"),"x":10 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf0"),"x":11 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf1"),"x":12 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf2"),"x":13 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf3"),"x":14 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf4"),"x":15 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf5"),"x":16 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf6"),"x":17 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf7"),"x":18 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf8"),"x":19 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf9"),"x":20 }Use Array Operations with the CursorThe following procedure lets you manipulate a cursor object as if it were an array:1.In the mongo shell,query the testData collection and assign the resulting cursor object to the c variable:var c = db.testData.find()2.To ﬁnd the document at the array index 4,use the following operation:printjson( c [ 4 ] )MongoDB returns the following:{"_id":ObjectId("51a7dc7b2cacf40b79990bea"),"x":5 }When you access documents in a cursor using the array index notation,mongo ﬁrst calls thecursor.toArray() method and loads into RAM all documents returned by the cursor.The index is thenapplied to the resulting array.This operation iterates the cursor completely and exhausts the cursor.For very large result sets,mongo may run out of available memory.For more information on the cursor,see crud-read-cursor.Query for Speciﬁc DocumentsMongoDB has a rich query system that allows you to select and ﬁlter the documents in a collection along speciﬁcﬁelds and values.See Query Documents (page 60) and Read Operations (page 31) for a full account of queries inMongoDB.22 Chapter 1.Install MongoDBMongoDB Documentation,Release 2.4.8In this procedure,you query for speciﬁc documents in the testData collection by passing a “query document” as aparameter to the find() method.Aquery document speciﬁes the criteria the query must match to return a document.In the mongo shell,query for all documents where the x ﬁeld has a value of 18 by passing the { x:18 } querydocument as a parameter to the find() method:db.testData.find( { x:18 } )MongoDB returns one document that ﬁts this criteria:{"_id":ObjectId("51a7dc7b2cacf40b79990bf7"),"x":18 }Return a Single Document froma CollectionWith the findOne() method you can return a single document from a MongoDB collection.The findOne()method takes the same parameters as find(),but returns a document rather than a cursor.To retrieve one document fromthe testData collection,issue the following command:db.testData.findOne()For more information on querying for documents,see the Query Documents (page 60) and Read Operations (page 31)documentation.Limit the Number of Documents in the Result SetTo increase performance,you can constrain the size of the result by limiting the amount of data your application mustreceive over the network.To specify the maximum number of documents in the result set,call the limit() method on a cursor,as in thefollowing command:db.testData.find().limit(3)MongoDB will return the following result,with different ObjectId (page 129) values:{"_id":ObjectId("51a7dc7b2cacf40b79990be6"),"x":1 }{"_id":ObjectId("51a7dc7b2cacf40b79990be7"),"x":2 }{"_id":ObjectId("51a7dc7b2cacf40b79990be8"),"x":3 }Next Steps with MongoDBFor more information on manipulating the documents in a database as you continue to learn MongoDB,consider thefollowing resources:• MongoDB CRUD Operations (page 27)• SQL to MongoDB Mapping Chart (page 85)• MongoDB Drivers and Client Libraries (page 95)1.2.2 Generate Test DataThis tutorial describes how to quickly generate test data as you need to test basic MongoDB operations.1.2.First Steps with MongoDB 23MongoDB Documentation,Release 2.4.8Insert Multiple Documents Using a For LoopYou can add documents to a new or existing collection by using a JavaScript for loop run fromthe mongo shell.1.From the mongo shell,insert new documents into the testData collection using the following for loop.Ifthe testData collection does not exist,MongoDB creates the collection implicitly.for (var i = 1;i <= 25;i++) db.testData.insert( { x:i } )2.Use ﬁnd() to query the collection:db.testData.find()The mongo shell displays the ﬁrst 20 documents in the collection.Your ObjectId (page 129) values will bedifferent:{"_id":ObjectId("51a7dc7b2cacf40b79990be6"),"x":1 }{"_id":ObjectId("51a7dc7b2cacf40b79990be7"),"x":2 }{"_id":ObjectId("51a7dc7b2cacf40b79990be8"),"x":3 }{"_id":ObjectId("51a7dc7b2cacf40b79990be9"),"x":4 }{"_id":ObjectId("51a7dc7b2cacf40b79990bea"),"x":5 }{"_id":ObjectId("51a7dc7b2cacf40b79990beb"),"x":6 }{"_id":ObjectId("51a7dc7b2cacf40b79990bec"),"x":7 }{"_id":ObjectId("51a7dc7b2cacf40b79990bed"),"x":8 }{"_id":ObjectId("51a7dc7b2cacf40b79990bee"),"x":9 }{"_id":ObjectId("51a7dc7b2cacf40b79990bef"),"x":10 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf0"),"x":11 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf1"),"x":12 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf2"),"x":13 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf3"),"x":14 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf4"),"x":15 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf5"),"x":16 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf6"),"x":17 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf7"),"x":18 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf8"),"x":19 }{"_id":ObjectId("51a7dc7b2cacf40b79990bf9"),"x":20 }1.The find() returns a cursor.To iterate the cursor and return more documents use the it operation in themongo shell.The mongo shell will exhaust the cursor,and return the following documents:{"_id":ObjectId("51a7dce92cacf40b79990bfc"),"x":21 }{"_id":ObjectId("51a7dce92cacf40b79990bfd"),"x":22 }{"_id":ObjectId("51a7dce92cacf40b79990bfe"),"x":23 }{"_id":ObjectId("51a7dce92cacf40b79990bff"),"x":24 }{"_id":ObjectId("51a7dce92cacf40b79990c00"),"x":25 }Insert Multiple Documents with a mongo Shell FunctionYou can create a JavaScript function in your shell session to generate the above data.The insertData() JavaScriptfunction,shown here,creates new data for use in testing or training by either creating a new collection or appendingdata to an existing collection:function insertData(dbName,colName,num) {var col = db.getSiblingDB(dbName).getCollection(colName);for (i = 0;i < num;i++) {col.insert({x:i});24 Chapter 1.Install MongoDBMongoDB Documentation,Release 2.4.8}print(col.count());}The insertData() function takes three parameters:a database,a new or existing collection,and the number ofdocuments to create.The function creates documents with an x ﬁeld that is set to an incremented integer,as in thefollowing example documents:{"_id":ObjectId("51a4da9b292904caffcff6eb"),"x":0 }{"_id":ObjectId("51a4da9b292904caffcff6ec"),"x":1 }{"_id":ObjectId("51a4da9b292904caffcff6ed"),"x":2 }Store the function in your.mongorc.js ﬁle.The mongo shell loads the function for you every time you start a session.ExampleSpecify database name,collection name,and the number of documents to insert as arguments to insertData().insertData("test","testData",400)This operation inserts 400 documents into the testData collection in the test database.If the collection anddatabase do not exist,MongoDB creates themimplicitly before inserting documents.See also:MongoDB CRUD Concepts (page 29) and Data Models (page 97).1.2.First Steps with MongoDB 25MongoDB Documentation,Release 2.4.826 Chapter 1.Install MongoDBCHAPTER 2MongoDB CRUD OperationsMongoDB provides rich semantics for reading and manipulating data.CRUD stands for create,read,update,anddelete.These terms are the foundation for all interactions with the database.MongoDB CRUD Introduction (page 27) An introduction to the MongoDB data model as well as queries and datamanipulations.MongoDB CRUD Concepts (page 29) The core documentation of query and data manipulation.MongoDB CRUD Tutorials (page 58) Examples of basic query and data modiﬁcation operations.MongoDB CRUD Reference (page 82) Reference material for the query and data manipulation interfaces.2.1 MongoDB CRUD IntroductionMongoDB stores data in the formof documents,which are JSON-like ﬁeld and value pairs.Documents are analogousto structures in programming languages that associate keys with values,where keys may hold other pairs of keys andvalues (e.g.dictionaries,hashes,maps,and associative arrays).Formally,MongoDBdocuments are BSON documents,which is a binary representation of JSON with additional type information.For more information,see Documents(page 122).Figure 2.1:A MongoDB document.MongoDB stores all documents in collections.A collection is a group of related documents that have a set of sharedcommon indexes.Collections are analogous to a table in relational databases.27MongoDB Documentation,Release 2.4.8Figure 2.2:A collection of MongoDB documents.2.1.1 Database OperationsQueryIn MongoDB a query targets a speciﬁc collection of documents.Queries specify criteria,or conditions,that identifythe documents that MongoDB returns to the clients.A query may include a projection that speciﬁes the ﬁelds fromthe matching documents to return.You can optionally modify queries to impose limits,skips,and sort orders.In the following diagram,the query process speciﬁes a query criteria and a sort modiﬁer:Data ModiﬁcationData modiﬁcation refers to operations that create,update,or delete data.In MongoDB,these operations modify thedata of a single collection.For the update and delete operations,you can specify the criteria to select the documentsto update or remove.In the following diagram,the insert operation adds a new document to the users collection.2.1.2 Related FeaturesIndexesTo enhance the performance of common queries and updates,MongoDBhas full support for secondary indexes.Theseindexes allowapplications to store a viewof a portion of the collection in an efﬁcient data structure.Most indexes storean ordered representation of all values of a ﬁeld or a group of ﬁelds.Indexes may also enforce uniqueness (page 334),store objects in a geospatial representation (page 326),and facilitate text search (page 332).28 Chapter 2.MongoDB CRUD OperationsMongoDB Documentation,Release 2.4.8Figure 2.3:The stages of a MongoDB query with a query criteria and a sort modiﬁer.Read PreferenceFor replica sets and sharded clusters with replica set components,applications specify read preferences (page 405).Aread preference determines how the client direct read operations to the set.Write ConcernApplications can also control the behavior of write operations using write concern (page 46).Particularly usefulfor deployments with replica sets,the write concern semantics allow clients to specify the assurance that MongoDBprovides when reporting on the success of a write operation.AggregationIn addition to the basic queries,MongoDB provides several data aggregation features.For example,MongoDB canreturn counts of the number of documents that match a query,or return the number of distinct values for a ﬁeld,orprocess a collection of documents using a versatile stage-based data processing pipeline or map-reduce operations.2.2 MongoDB CRUD ConceptsThe Read Operations (page 31) and Write Operations (page 42) documents introduces the behavior and operations ofread and write operations for MongoDB deployments.Read Operations (page 31) Introduces all operations that select and return documents to clients,including the queryspeciﬁcations.Cursors (page 35) Queries return iterable objects,called cursors,that hold the full result set of the query re-quest.Query Optimization (page 36) Analyze and improve query performance.2.2.MongoDB CRUD Concepts 29MongoDB Documentation,Release 2.4.8Figure 2.4:The stages of a MongoDB insert operation.30 Chapter 2.MongoDB CRUD OperationsMongoDB Documentation,Release 2.4.8Distributed Queries (page 38) Describes how sharded clusters and replica sets affect the performance of readoperations.Write Operations (page 42) Introduces data create and modify operations,their behavior,and performances.Write Concern (page 46) Describes the kind of guarantee MongoDB provides when reporting on the successof a write operation.Distributed Write Operations (page 49) Describes howMongoDB directs write operations on sharded clustersand replica sets and the performance characteristics of these operations.2.2.1 Read OperationsRead operations,or queries,retrieve data stored in the database.In MongoDB,queries select documents froma singlecollection.Queries specify criteria,or conditions,that identify the documents that MongoDB returns to the clients.A query mayinclude a projection that speciﬁes the ﬁelds fromthe matching documents to return.The projection limits the amountof data that MongoDB returns to the client over the network.Query InterfaceFor query operations,MongoDB provide a db.collection.find() method.The method accepts both the querycriteria and projections and returns a cursor (page 35) to the matching documents.You can optionally modify thequery to impose limits,skips,and sort orders.The following diagramhighlights the components of a MongoDB query operation:Figure 2.5:The components of a MongoDB ﬁnd operation.The next diagramshows the same query in SQL:Figure 2.6:The components of a SQL SELECT statement.Example2.2.MongoDB CRUD Concepts 31MongoDB Documentation,Release 2.4.8db.users.find( { age:{ $gt:18 } },{ name:1,address:1 } ).limit(5)This query selects the documents in the users collection that match the condition age is greater than 18.To specifythe greater than condition,query criteria uses the greater than (i.e.$gt) query selection operator.The query returnsat most 5 matching documents (or more precisely,a cursor to those documents).The matching documents will returnwith only the _id,name and address ﬁelds.See Projections (page 32) for details.SeeSQL to MongoDB Mapping Chart (page 85) for additional examples of MongoDBqueries and the corresponding SQLstatements.Query BehaviorMongoDB queries exhibit the following behavior:• All queries in MongoDB address a single collection.• You can modify the query to impose limits,skips,and sort orders.• The order of documents returned by a query is not deﬁned and is not necessarily consistent unless you specify asort().• Operations that modify existing documents (page 67) (i.e.updates) use the same query syntax as queries to selectdocuments to update.• In aggregation (page 281) pipeline,the $match pipeline stage provides access to MongoDB queries.MongoDB provides a db.collection.findOne() method as a special case of find() that returns a singledocument.Query StatementsConsider the following diagramof the query process that speciﬁes a query criteria and a sort modiﬁer:In the diagram,the query selects documents fromthe users collection.Using a query selection operatorto deﬁne the conditions for matching documents,the query selects documents that have age greater than (i.e.$gt)18.Then the sort() modiﬁer sorts the results by age in ascending order.For additional examples of queries,see Query Documents (page 60).ProjectionsQueries in MongoDBreturn all ﬁelds in all matching documents by default.To limit the amount of data that MongoDBsends to applications,include a projection in the queries.By projecting results with a subset of ﬁelds,applicationsreduce their network overhead and processing requirements.Projections,which are the the second argument to the find() method,may either specify a list of ﬁelds to return orlist ﬁelds to exclude in the result documents.Important:Except for excluding the _id ﬁeld in inclusive projections,you cannot mix exclusive and inclusiveprojections.Consider the following diagramof the query process that speciﬁes a query criteria and a projection:32 Chapter 2.MongoDB CRUD OperationsMongoDB Documentation,Release 2.4.8Figure 2.7:The stages of a MongoDB query with a query criteria and a sort modiﬁer.Figure 2.8:The stages of a MongoDB query with a query criteria and projection.MongoDB only transmits theprojected data to the clients.2.2.MongoDB CRUD Concepts 33MongoDB Documentation,Release 2.4.8In the diagram,the query selects fromthe users collection.The criteria matches the documents that have age equalto 18.Then the projection speciﬁes that only the name ﬁeld should return in the matching documents.Projection ExamplesExclude One Field Froma Result Setdb.records.find( {"user_id":{ $lt:42} },{ history:0} )This query selects a number of documents in the records collection that match the query {"user_id":{$lt:42} },but excludes the history ﬁeld.Return Two ﬁelds and the _id Fielddb.records.find( {"user_id":{ $lt:42} },{"name":1,"email":1} )This query selects a number of documents in the records collection that match the query {"user_id":{$lt:42} },but returns documents that have the _id ﬁeld (implicitly included) as well as the name and emailﬁelds.Return Two Fields and Exclude _iddb.records.find( {"user_id":{ $lt:42} },{"_id":0,"name":1,"email":1 } )This query selects a number of documents in the records collection that match the query {"user_id":{$lt:42} },but only returns the name and email ﬁelds.SeeLimit Fields to Return from a Query (page 63) for more examples of queries with projection statements.Projection BehaviorMongoDB projections have the following properties:• In MongoDB,the _id ﬁeld is always included in results unless explicitly excluded.• For ﬁelds that contain arrays,MongoDB provides the following projection operators:$elemMatch,$slice,$.• For related projection functionality in the aggregation framework (page 281) pipeline,use the $projectpipeline stage.Related ConceptsThe following documents further describe read operations:Cursors (page 35) Queries return iterable objects,called cursors,that hold the full result set of the query request.Query Optimization (page 36) Analyze and improve query performance.Query Plans (page 37) MongoDB processes and executes using plans developed to return results as efﬁciently aspossible.Distributed Queries (page 38) Describes how sharded clusters and replica sets affect the performance of read opera-tions.34 Chapter 2.MongoDB CRUD OperationsMongoDB Documentation,Release 2.4.8CursorsIn the mongo shell,the primary method for the read operation is the db.collection.find() method.Thismethod queries a collection and returns a cursor to the returning documents.To access the documents,you need to iterate the cursor.However,in the mongo shell,if the returned cursor is notassigned to a variable using the var keyword,then the cursor is automatically iterated up to 20 times1to print up tothe ﬁrst 20 documents in the results.For example,in the mongo shell,the following read operation queries the inventory collection for documents thathave type equal to ’food’ and automatically print up to the ﬁrst 20 matching documents:db.inventory.find( { type:'food'} );To manually iterate the cursor to access the documents,see Iterate a Cursor in the mongo Shell (page 65).Cursor BehaviorsClosure of Inactive Cursors By default,the server will automatically close the cursor after 10 minutes of inactivityor if client has exhausted the cursor.To override this behavior,you can specify the noTimeout wire protocol ﬂag2in your query;however,you should either close the cursor manually or exhaust the cursor.In the mongo shell,youcan set the noTimeout ﬂag:var myCursor = db.inventory.find().addOption(DBQuery.Option.noTimeout);See your driver (page 95) documentation for information on setting the noTimeout ﬂag.For the mongo shell,seecursor.addOption() for a complete list of available cursor ﬂags.Cursor Isolation Because the cursor is not isolated during its lifetime,intervening write operations on a documentmay result in a cursor that returns a document more than once if that document has changed.To handle this situation,see the information on snapshot mode (page 586).Cursor Batches The MongoDB server returns the query results in batches.Batch size will not exceed the maximumBSON document size.For most queries,the ﬁrst batch returns 101 documents or just enough documents to exceed 1megabyte.Subsequent batch size is 4 megabytes.To override the default size of the batch,see batchSize() andlimit().For queries that include a sort operation without an index,the server must load all the documents in memory to performthe sort and will return all documents in the ﬁrst batch.As you iterate through the cursor and reach the end of the returned batch,if there are more results,cursor.next()will perform a getmore operation to retrieve the next batch.To see how many documents remain in the batchas you iterate the cursor,you can use the objsLeftInBatch() method,as in the following example:var myCursor = db.inventory.find();var myFirstDocument = myCursor.hasNext()?myCursor.next():null;myCursor.objsLeftInBatch();1You can use the DBQuery.shellBatchSize to change the number of iteration from the default value 20.See Executing Queries(page 214) for more information.2http://docs.mongodb.org/meta-driver/latest/legacy/mongodb-wire-protocol2.2.MongoDB CRUD Concepts 35MongoDB Documentation,Release 2.4.8Cursor Information You can use the command cursorInfo to retrieve the following information on cursors:• total number of open cursors• size of the client cursors in current use• number of timed out cursors since the last server restartConsider the following example:db.runCommand( { cursorInfo:1 } )The result fromthe command returns the following document:{"totalOpen":<number>,"clientCursors_size":<number>,"timedOut":<number>,"ok":1}Query OptimizationIndexes improve the efﬁciency of read operations by reducing the amount of data that query operations need to process.This simpliﬁes the work associated with fulﬁlling queries within MongoDB.Create an Index to Support Read Operations If your application queries a collection on a particular ﬁeld or ﬁelds,then an index on the queried ﬁeld or ﬁelds can prevent the query from scanning the whole collection to ﬁnd andreturn the query results.For more information about indexes,see the complete documentation of indexes in MongoDB(page 318).ExampleAn application queries the inventory collection on the type ﬁeld.The value of the type ﬁeld is user-driven.var typeValue = <someUserInput>;db.inventory.find( { type:typeValue } );To improve the performance of this query,add an ascending,or a descending,index to the inventory collectionon the type ﬁeld.3In the mongo shell,you can create indexes using the db.collection.ensureIndex()method:db.inventory.ensureIndex( { type:1 } )This index can prevent the above query on type fromscanning the whole collection to return the results.To analyze the performance of the query with an index,see Analyze Query Performance (page 66).In addition to optimizing read operations,indexes can support sort operations and allow for a more efﬁcient storageutilization.See db.collection.ensureIndex()and Indexing Tutorials (page 338) for more information aboutindex creation.3For single-ﬁeld indexes,the selection between ascending and descending order is immaterial.For compound indexes,the selection is important.See indexing order (page 323) for more details.36 Chapter 2.MongoDB CRUD OperationsMongoDB Documentation,Release 2.4.8Query Selectivity Some query operations are not selective.These operations cannot use indexes effectively orcannot use indexes at all.The inequality operators $nin and $ne are not very selective,as they often match a large portion of the index.As aresult,in most cases,a $nin or $ne query with an index may performno better than a $nin or $ne query that mustscan all documents in a collection.Queries that specify regular expressions,with inline JavaScript regular expressions or $regex operator expressions,cannot use an index with one exception.Queries that specify regular expression with anchors at the beginning of astring can use an index.Covering a Query An index covers (page 369) a query,a covered query,when:• all the ﬁelds in the query (page 60) are part of that index,and• all the ﬁelds returned in the documents that match the query are in the same index.For these queries,MongoDB does not need to inspect documents outside of the index.This is often more efﬁcientthan inspecting entire documents.ExampleGiven a collection inventory with the following index on the type and item ﬁelds:{ type:1,item:1 }This index will cover the following query on the type and item ﬁelds,which returns only the item ﬁeld:db.inventory.find( { type:"food",item:/^c/},{ item:1,_id:0 } )However,the index will not cover the following query,which returns the item ﬁeld and the _id ﬁeld:db.inventory.find( { type:"food",item:/^c/},{ item:1 } )See Create Indexes that Support Covered Queries (page 369) for more information on the behavior and use of coveredqueries.Query PlansThe MongoDBquery optimizer processes queries and chooses the most efﬁcient query plan for a query given the avail-able indexes.The query systemthen uses this query plan each time the query runs.The query optimizer occasionallyreevaluates query plans as the content of the collection changes to ensure optimal query plans.You can use the explain() method to view statistics about the query plan for a given query.This information canhelp as you develop indexing strategies (page 367).Query Optimization To create a new query plan,the query optimizer:1.runs the query against several candidate indexes in parallel.2.records the matches in a common results buffer or buffers.• If the candidate plans include only ordered query plans,there is a single common results buffer.• If the candidate plans include only unordered query plans,there is a single common results buffer.2.2.MongoDB CRUD Concepts 37MongoDB Documentation,Release 2.4.8• If the candidate plans include both ordered query plans and unordered query plans,there are two commonresults buffers,one for the ordered plans and the other for the unordered plans.If an index returns a result already returned by another index,the optimizer skips the duplicate match.In thecase of the two buffers,both buffers are de-duped.3.stops the testing of candidate plans and selects an index when one of the following events occur:• An unordered query plan has returned all the matching results;or• An ordered query plan has returned all the matching results;or• An ordered query plan has returned a threshold number of matching results:– Version 2.0:Threshold is the query batch size.The default batch size is 101.– Version 2.2:Threshold is 101.The selected index becomes the index speciﬁed in the query plan;future iterations of this query or queries with thesame query pattern will use this index.Query pattern refers to query select conditions that differ only in the values,asin the following two queries with the same query pattern:db.inventory.find( { type:'food'} )db.inventory.find( { type:'utensil'} )Query Plan Revision As collections change over time,the query optimizer deletes the query plan and re-evaluatesafter any of the following events:• The collection receives 1,000 write operations.• The reIndex rebuilds the index.• You add or drop an index.• The mongod process restarts.Distributed QueriesRead Operations to Sharded Clusters Sharded clusters allow you to partition a data set among a cluster ofmongod instances in a way that is nearly transparent to the application.For an overview of sharded clusters,seethe Sharding (page 491) section of this manual.For a sharded cluster,applications issue operations to one of the mongos instances associated with the cluster.Read operations on sharded clusters are most efﬁcient when directed to a speciﬁc shard.Queries to sharded collectionsshould include the collection’s shard key (page 503).When a query includes a shard key,the mongos can use clustermetadata fromthe conﬁg database (page 500) to route the queries to shards.If a query does not include the shard key,the mongos must direct the query to all shards in the cluster.These scattergather queries can be inefﬁcient.On larger clusters,scatter gather queries are unfeasible for routine operations.For more information on read operations in sharded clusters,see the Sharded Cluster Query Routing (page 507) andShard Keys (page 503) sections.Read Operations to Replica Sets Replica sets use read preferences to determine where and how to route readoperations to members of the replica set.By default,MongoDB always reads data from a replica set’s primary.Youcan modify that behavior by changing the read preference mode (page 488).You can conﬁgure the read preference mode (page 488) on a per-connection or per-operation basis to allowreads fromsecondaries to:38 Chapter 2.MongoDB CRUD OperationsMongoDB Documentation,Release 2.4.8Figure 2.9:Diagramof a sharded cluster.2.2.MongoDB CRUD Concepts 39MongoDB Documentation,Release 2.4.8Figure 2.10:Read operations to a sharded cluster.Query criteria includes the shard key.The query router mongoscan target the query to the appropriate shard or shards.40 Chapter 2.MongoDB CRUD OperationsMongoDB Documentation,Release 2.4.8Figure 2.11:Read operations to a sharded cluster.Query criteria does not include the shard key.The query routermongos must broadcast query to all shards for the collection.2.2.MongoDB CRUD Concepts 41MongoDB Documentation,Release 2.4.8• reduce latency in multi-data-center deployments,• improve read throughput by distributing high read-volumes (relative to write volume),• for backup operations,and/or• to allow reads during failover (page 396) situations.Figure 2.12:Read operations to a replica set.Default read preference routes the read to the primary.Read preferenceof nearest routes the read to the nearest member.Read operations fromsecondary members of replica sets are not guaranteed to reﬂect the current state of the primary,and the state of secondaries will trail the primary by some amount of time.Often,applications don’t rely on this kindof strict consistency,but application developers should always consider the needs of their application before settingread preference.For more information on read preference or on the read preference modes,see Read Preference (page 405) and ReadPreference Modes (page 488).2.2.2 Write OperationsA write operation is any operation that creates or modiﬁes data in the MongoDB instance.In MongoDB,writeoperations target a single collection.All write operations in MongoDB are atomic on the level of a single document.There are three classes of write operations in MongoDB:insert,update,and remove.Insert operations add newdata toa collection.Update operations modify existing data,and remove operations delete data from a collection.No insert,update,or remove can affect more than one document atomically.For the update and remove operations,you can specify criteria,or conditions,that identify the documents to update orremove.These operations use the same query syntax to specify the criteria as read operations (page 31).After issuing these modiﬁcation operations,MongoDB allows applications to determine the level of acknowledgmentreturned fromthe database.See Write Concern (page 46).42 Chapter 2.MongoDB CRUD OperationsMongoDB Documentation,Release 2.4.8CreateCreate operations add new documents to a collection.In MongoDB,the db.collection.insert() methodperforms create operations.The following diagramhighlights the components of a MongoDB insert operation:Figure 2.13:The components of a MongoDB insert operations.The following diagramshows the same query in SQL:Figure 2.14:The components of a SQL INSERT statement.ExampleThe following operation inserts a newdocuments into the users collection.The newdocument has four ﬁelds name,age,and status,and an _id ﬁeld.MongoDB always adds the _id ﬁeld to the new document if that ﬁeld does notexist.db.users.insert({name:"sue",age:26,status:"A"})This operation inserts a new document into the users collection.The new document has four ﬁelds:name,age,status,and an _id ﬁeld.MongoDB always adds the _id ﬁeld to a new document if the ﬁeld does not exist.For more information,see db.collection.insert() and Insert Documents (page 59).2.2.MongoDB CRUD Concepts 43MongoDB Documentation,Release 2.4.8Some updates also create records.If an update operation speciﬁes the upsert ﬂag and there are no documents thatmatch the query portion of the update operation,then MongoDB will convert the update into an insert.With an upsert,applications can decide between performing an update or an insert operation using just a single call.Both the update() method and the save() method can perform an upsert.See update() and save() fordetails on performing an upsert with these methods.SeeSQL to MongoDB Mapping Chart (page 85) for additional examples of MongoDB write operations and the corre-sponding SQL statements.Insert BehaviorIf you add a new document without the _id ﬁeld,the client library or the mongod instance adds an _id ﬁeld andpopulates the ﬁeld with a unique ObjectId.If you specify the _id ﬁeld,the value must be unique within the collection.For operations with write concern(page 46),if you try to create a document with a duplicate _id value,mongod returns a duplicate key exception.UpdateUpdate operations modify existing documents in a collection.In MongoDB,db.collection.update() and thedb.collection.save() methods performupdate operations.The db.collection.update() method canaccept a query criteria to determine which documents to update as well as an option to update multiple rows.Themethod can also accept options that affect its behavior such as the multi option to update multiple documents.The following diagramhighlights the components of a MongoDB update operation:Figure 2.15:The components of a MongoDB update operation.The following diagramshows the same query in SQL:Figure 2.16:The components of a SQL UPDATE statement.44 Chapter 2.MongoDB CRUD OperationsMongoDB Documentation,Release 2.4.8Exampledb.users.update({ age:{ $gt:18 } },{ $set:{ status:"A"} },{ multi:true })This update operation on the users collection sets the status ﬁeld to A for the documents that match the criteriaof age greater than 18.For more information,see db.collection.update() and db.collection.save(),and Modify Docu-ments (page 67) for examples.Update BehaviorBy default,the db.collection.update()method updates a single document.However,with the multioption,update() can update all documents in a collection that match a query.The db.collection.update() method either updates speciﬁc ﬁelds in the existing document or replaces thedocument.See db.collection.update() for details.When performing update operations that increase the document size beyond the allocated space for that document,theupdate operation relocates the document on disk and may reorder the document ﬁelds depending on the type of update.The db.collection.save() method replaces a document and can only update a single document.Seedb.collection.save() and Insert Documents (page 59) for more informationDeleteDelete operations remove documents from a collection.In MongoDB,db.collection.remove() method per-forms delete operations.The db.collection.remove() method can accept a query criteria to determine whichdocuments to remove.The following diagramhighlights the components of a MongoDB remove operation:Figure 2.17:The components of a MongoDB remove operation.The following diagramshows the same query in SQL:Exampledb.users.remove({ status:"D"})2.2.MongoDB CRUD Concepts 45MongoDB Documentation,Release 2.4.8Figure 2.18:The components of a SQL DELETE statement.This delete operation on the users collection removes all documents that match the criteria of status equal to D.For more information,see db.collection.remove() method and Remove Documents (page 68).Remove BehaviorBy default,db.collection.remove() method removes all documents that match its query.However,themethod can accept a ﬂag to limit the delete operation to a single document.Isolation of Write OperationsThe modiﬁcation of a single document is always atomic,even if the write operation modiﬁes multiple sub-documents