MongoDB Manual

668
MongoDB Documentation Release 2.4.9 MongoDB Documentation Project January 14, 2014

description

MongoDB Manual

Transcript of MongoDB Manual

  • MongoDB DocumentationRelease 2.4.9

    MongoDB Documentation Project

    January 14, 2014

  • 2

  • Contents

    1 Install MongoDB 31.1 Installation Guides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 First Steps with MongoDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

    2 MongoDB CRUD Operations 272.1 MongoDB CRUD Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272.2 MongoDB CRUD Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292.3 MongoDB CRUD Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582.4 MongoDB CRUD Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

    3 Data Models 973.1 Data Modeling Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 973.2 Data Modeling Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 993.3 Data Model Examples and Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1063.4 Data Model Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

    4 Administration 1354.1 Administration Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1354.2 Administration Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1704.3 Administration Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223

    5 Security 2375.1 Security Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2375.2 Security Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2395.3 Security Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2455.4 Security Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267

    6 Aggregation 2776.1 Aggregation Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2776.2 Aggregation Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2816.3 Aggregation Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2926.4 Aggregation Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308

    7 Indexes 3137.1 Index Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3137.2 Index Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3187.3 Indexing Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3397.4 Indexing Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374

    1

  • 8 Replication 3778.1 Replication Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3778.2 Replication Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3818.3 Replica Set Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4198.4 Replication Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466

    9 Sharding 4819.1 Sharding Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4819.2 Sharding Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4869.3 Sharded Cluster Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5089.4 Sharding Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549

    10 Frequently Asked Questions 55710.1 FAQ: MongoDB Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55710.2 FAQ: MongoDB for Application Developers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56010.3 FAQ: The mongo Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57010.4 FAQ: Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57210.5 FAQ: Sharding with MongoDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57610.6 FAQ: Replica Sets and Replication in MongoDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58210.7 FAQ: MongoDB Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58510.8 FAQ: Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58910.9 FAQ: MongoDB Diagnostics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592

    11 Release Notes 59711.1 Current Stable Release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59711.2 Previous Stable Releases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61511.3 Other MongoDB Release Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64011.4 MongoDB Version Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641

    12 About MongoDB Documentation 64312.1 License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64312.2 Editions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64312.3 Version and Revisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64412.4 Report an Issue or Make a Change Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64412.5 Contribute to the Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644

    Index 661

    2

  • MongoDB Documentation, Release 2.4.9

    See About MongoDB Documentation (page 643) 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 Manual1 for a PDFedition of all MongoDB Reference Material.

    1http://docs.mongodb.org/v2.4/MongoDB-reference-manual.pdf

    Contents 1

  • MongoDB Documentation, Release 2.4.9

    2 Contents

  • CHAPTER 1

    Install MongoDB

    MongoDB runs on most platforms and supports both 32-bit and 64-bit architectures.

    1.1 Installation Guides

    SeeRelease Notes (page 597) for information about specific releases of MongoDB.

    1.1.1 Linux

    Install on Linux (page 3)

    Install on Linux

    These documents provide instructions to install MongoDB for various Linux systems.

    Recommended

    For 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 Installation

    Although 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 from the MongoDB archives.

    3

  • MongoDB Documentation, Release 2.4.9

    Install 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 official MongoDB packages aregenerally more up to date.

    Packages The MongoDB downloads repository contains two packages:

    mongo-10gen-server

    This package contains the mongod and mongos daemons from the latest stable release and associated con-figuration and init scripts. Additionally, you can use this package to install daemons from a previous release(page 4) of MongoDB.

    mongo-10gen

    This package contains all MongoDB tools from the 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 from which you may need to administer MongoDB systems.

    Install MongoDB

    Configure Package Management System (YUM) Create a /etc/yum.repos.d/mongodb.repo file to holdthe following configuration 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 configuration:

    [mongodb]name=MongoDB Repositorybaseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/gpgcheck=0enabled=1

    If you are running a 32-bit system, which is not recommended for production deployments, use the following config-uration:

    [mongodb]name=MongoDB Repositorybaseurl=http://downloads-distro.mongodb.org/repo/redhat/os/i686/gpgcheck=0enabled=1

    Install 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-server

    When 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 specific release, append the version number, as in the following example:

    4 Chapter 1. Install MongoDB

  • MongoDB Documentation, Release 2.4.9

    yum install mongo-10gen-2.2.3 mongo-10gen-server-2.2.3

    This 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 file:

    exclude=mongo-10gen,mongo-10gen-server

    Control Scripts

    Warning: 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-7285a for 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-7285

    The packages include various control scripts, including the init script /etc/rc.d/init.d/mongod. These pack-ages configure MongoDB using the /etc/mongod.conf file in conjunction with the control scripts.

    As of version 2.4.9, there are no control scripts for mongos. mongos is only used in sharding deployments(page 486). You can use the mongod init script to derive your own mongos control script.

    Run MongoDBImportant: You must configure SELinux to allow MongoDB to start on Fedora systems. Administrators have twooptions:

    enable access to the relevant ports (e.g. 27017) for SELinux. See Configuration Options (page 242) for moreinformation on MongoDBs default ports (page 275).

    disable SELinux entirely. This requires a system reboot and may have larger implications for your deployment.

    Start MongoDB The MongoDB instance stores its data files in the /var/lib/mongo and its log files in/var/log/mongo, and run using the mongod user account. If you change the user that runs the MongoDB process,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 start

    You can verify that the mongod process has started successfully by checking the contents of the log file 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 on

    Stop MongoDB Stop the mongod process by issuing the following command (as root or with sudo):

    service mongod stop

    1.1. Installation Guides 5

  • MongoDB Documentation, Release 2.4.9

    Restart MongoDB You can restart the mongod process by issuing the following command (as root or with sudo):

    service mongod restart

    Follow the state of this process by watching the output in the /var/log/mongo/mongod.log file to watch forerrors or important messages from the 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 official 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 follow theinstructions 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-clients pack-ages provided by Ubuntu.

    Install MongoDB

    Configure 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 7F0CEB10

    Create a /etc/apt/sources.list.d/mongodb.list file using the following command.

    echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

    Now issue the following command to reload your repository:

    sudo apt-get update

    Install Packages Issue the following command to install the latest stable version of MongoDB:

    sudo apt-get install mongodb-10gen

    When this command completes, you have successfully installed MongoDB! Continue for configuration and start-upsuggestions.

    Manage Installed Versions You can use the mongodb-10gen package to install previous versions of MongoDB.To install a specific release, append the version number to the package name, as in the following example:

    apt-get install mongodb-10gen=2.2.3

    This 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.asc

    6 Chapter 1. Install MongoDB

  • MongoDB Documentation, Release 2.4.9

    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-selections

    Control Scripts The packages include various control scripts, including the init script/etc/rc.d/init.d/mongod. These packages configure MongoDB using the /etc/mongod.conf filein conjunction with the control scripts.

    As of version 2.4.9, there are no control scripts for mongos. mongos is only used in sharding deployments(page 486). You can use the mongod init script to derive your own mongos control script.

    Run MongoDB The MongoDB instance stores its data files in the /var/lib/mongo and its log files in/var/log/mongo, and run using the mongod user account. If you change the user that runs the MongoDB process,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 start

    You can verify that mongod has started successfully by checking the contents of the log file at/var/log/mongodb/mongodb.log.

    Stop MongoDB As needed, you may stop the mongod process by issuing the following command:

    sudo service mongodb stop

    Restart MongoDB You may restart the mongod process by issuing the following command:

    sudo service mongodb restart

    Install 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 officialMongoDB 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-clients pack-ages that your release of Debian may include.

    Install MongoDB

    Configure 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 7

  • MongoDB Documentation, Release 2.4.9

    Step 1: Import MongoDB PGP Key Issue the following command to add the MongoDB public GPG Key2 to thesystem key ring.

    sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10

    Step 2: Create a sources.list file for MongoDB Create a /etc/apt/sources.list.d/mongodb.listfile

    echo 'deb http://downloads-distro.mongodb.org/repo/debian-sysvinit dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

    Step 3: Reload Local Package Database Issue the following command to reload the local package database:

    sudo apt-get update

    Install Packages Issue the following command to install the latest stable version of MongoDB:

    sudo apt-get install mongodb-10gen

    When 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 specific release, append the version number to the package name, as in the following example:

    apt-get install mongodb-10gen=2.2.3

    This 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-selections

    Control Scripts The packages include various control scripts, including the init script/etc/rc.d/init.d/mongod. These packages configure MongoDB using the /etc/mongod.conf filein conjunction with the control scripts.

    As of version 2.4.9, there are no control scripts for mongos. mongos is only used in sharding deployments(page 486). You can use the mongod init script to derive your own mongos control script.

    Run MongoDB The MongoDB instance stores its data files in the /var/lib/mongo and its log files in/var/log/mongo, and run using the mongod user account. If you change the user that runs the MongoDB process,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 start

    You can verify that mongod has started successfully by checking the contents of the log file at/var/log/mongodb/mongodb.log.

    2http://docs.mongodb.org/10gen-gpg-key.asc

    8 Chapter 1. Install MongoDB

  • MongoDB Documentation, Release 2.4.9

    Stop MongoDB Issue the following command to stop mongod:

    sudo /etc/init.d/mongodb stop

    Restart MongoDB Issue the following command to restart mongod:

    sudo /etc/init.d/mongodb restart

    Install 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 MongoDB provides archives for both 64-bit and 32-bit Linux. Follow the installation procedureappropriate for your system.

    Install for 64-bit Linux

    Step 1: Download the Latest Release In a system shell, download the latest release for 64-bit Linux.

    curl -O http://downloads.mongodb.org/linux/mongodb-linux-x86_64-2.4.9.tgz

    You may optionally specify a different version to download.

    Step 2: Extract MongoDB From Archive Extract the files from the downloaded archive.

    tar -zxvf mongodb-linux-x86_64-2.4.9.tgz

    Step 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.4.9/ mongodb

    Step 4: Optional. Configure 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 find the MongoDB binaries in the bin/ directory within thearchive.

    Install for 32-bit Linux

    Step 1: Download the Latest Release In a system shell, download the latest release for 32-bit Linux.

    curl -O http://downloads.mongodb.org/linux/mongodb-linux-i686-2.4.9.tgz

    You may optionally specify a different version to download.

    Step 2: Extract MongoDB From Archive Extract the files from the downloaded archive.

    1.1. Installation Guides 9

  • MongoDB Documentation, Release 2.4.9

    tar -zxvf mongodb-linux-i686-2.4.9.tgz

    Step 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.4.9/ mongodb

    Step 4: Optional. Configure 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 find the MongoDB binaries in the bin/ directory within thearchive.

    Run MongoDB

    Set Up the Data Directory Before you start mongod for the first 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/db

    Step 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/db

    You must create the mongodb user separately.

    You can specify an alternate path for data files 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 system prompt.

    For example, if your PATH includes the location of the mongod binary, enter mongod at the system prompt.

    mongod

    If 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

    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 MongoDB

  • MongoDB Documentation, Release 2.4.9

    1.1.2 OS X

    Install MongoDB on OS X (page 11)

    Install MongoDB on OS X

    Platform SupportStarting 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 Homebrew3 or through the MongoDB Downloadsite.

    Install MongoDB with Homebrew

    Homebrew4 5 installs 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 updatebrew to the latest packages and installMongoDB:

    brew updatebrew install mongodb

    Later, if you need to upgrade MongoDB, run the following sequence of commands to update the MongoDB installationon your system:

    brew updatebrew upgrade mongodb

    Optionally, you can choose to build MongoDB from source. Use the following command to build MongoDB withSSL support:

    brew install mongodb --with-openssl

    You can also install the latest development release of MongoDB for testing and development with the followingcommand:

    brew install mongodb --devel

    Manual Installation

    Step 1: Download the Latest Release In a system shell, download the latest release for 64-bit OS X.

    curl -O http://downloads.mongodb.org/osx/mongodb-osx-x86_64-2.4.9.tgz

    You may optionally specify a different version to download.

    3http://brew.sh/4http://brew.sh/5 Homebrew requires some initial setup and configuration. This configuration is beyond the scope of this document.

    1.1. Installation Guides 11

  • MongoDB Documentation, Release 2.4.9

    Step 2: Extract MongoDB From Archive Extract the files from the downloaded archive.

    tar -zxvf mongodb-osx-x86_64-2.4.9.tgz

    Step 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.4.9/ mongodb

    Step 4: Optional. Configure 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 find the MongoDB binaries in the bin/ directory within thearchive.

    Run MongoDB

    Set Up the Data Directory Before you start mongod for the first 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/db

    Step 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/db

    You must create the mongodb user separately.

    You can specify an alternate path for data files 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 system prompt.

    For example, if your PATH includes the location of the mongod binary, enter mongod at the system prompt.

    mongod

    If 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

    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.

    12 Chapter 1. Install MongoDB

  • MongoDB Documentation, Release 2.4.9

    1.1.3 Windows

    Install MongoDB on Windows (page 13)

    Install MongoDB on Windows

    Platform SupportStarting in version 2.2, MongoDB does not support Windows XP. Please use a more recent version of Windows to usemore recent releases of MongoDB.

    Important: If you are running any edition of Windows Server 2008 R2 or Windows 7, please install a hotfix toresolve an issue with memory mapped files on Windows6.

    Download MongoDB for Windows

    There are three builds of MongoDB for Windows:

    MongoDB for 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 WindowsPlatform and 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 MongoDB are only intended for older systems and for use in testing and development systems. 32-bit versionsof MongoDB only support databases smaller than 2GB.

    TipTo find which version of Windows you are running, enter the following command in the Command Prompt:

    wmic os get osarchitecture

    1. Download the latest production release of MongoDB from the 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, find the MongoDB download file, 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 from the popup menu.

    (c) In the Command Prompt, issue the following commands:

    6http://support.microsoft.com/kb/27312847http://www.mongodb.org/downloads

    1.1. Installation Guides 13

  • MongoDB Documentation, Release 2.4.9

    cd \move C:\mongodb-win32-* C:\mongodb

    Note: 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 MongoDB

    Set Up the Data Directory MongoDB requires a data folder to store its files. 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\db

    You can specify an alternate path for data files using the --dbpath option to mongod.exe.

    Start MongoDB To start MongoDB, execute from the Command Prompt:

    C:\mongodb\bin\mongod.exe

    This 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 blockingsome 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 allow mongod.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\data

    If 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.exe

    Note: Executing the command start C:\mongodb\bin\mongo.exewill automatically start the mongo.exeshell in a separate Command Prompt window.

    14 Chapter 1. Install MongoDB

  • MongoDB Documentation, Release 2.4.9

    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 MongoDB8 for more information.

    MongoDB as a Windows Service

    New 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.

    Configure 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 specific directory for MongoDB log files:

    md C:\mongodb\log

    2. Optional. Create a configuration file for the logpath option for MongoDB in the Command Prompt by issuingthis command:

    echo logpath=C:\mongodb\log\mongo.log > C:\mongodb\mongod.cfg

    Note: Consider setting the logappend option. If you do not, mongod.exe will delete the contents of the existinglog file 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 --install

    Modify the path to the mongod.cfg file 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 MongoDB

    8http://docs.mongodb.org/ecosystem/drivers/csharp

    1.1. Installation Guides 15

  • MongoDB Documentation, Release 2.4.9

    If you wish to use an alternate path for your dbpath specify it in the config file (e.g. C:\mongodb\mongod.cfg)on that you specified in the --install operation. You may also specify --dbpath on the command line; however,always prefer the configuration file.

    If you have not set up the data directory, set up the data directory (page 14) where MongoDB will store its data files.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 MongoDB

    To remove the MongoDB service:

    C:\mongodb\bin\mongod.exe --remove

    1.1.4 MongoDB Enterprise

    Install MongoDB Enterprise (page 16)

    Install MongoDB Enterprise

    New in version 2.2.

    MongoDB Enterprise9 is available on four platforms and contains support for several features related to security andmonitoring.

    Required Packages

    Changed 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 17).

    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:

    9http://www.mongodb.com/products/mongodb-enterprise

    16 Chapter 1. Install MongoDB

  • MongoDB Documentation, Release 2.4.9

    sudo zypper install libopenssl0_9_8 libsnmp15 slessp1-libsnmp15 snmp-mibs cyrus-sasl cyrus-sasl-devel cyrus-sasl-gssapi

    Earlier 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 snmpd

    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 system repositories:

    sudo rpm -ivh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

    sudo yum update -y

    When 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-mibs

    Note: Before 2.4.4, MongoDB Enterprise 2.4 for SUSE requires libgsasl11 which is not available in the defaultrepositories for SUSE.

    Install MongoDB Enterprise Binaries

    When you have installed the required packages, and downloaded the Enterprise packages12 you 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.4.9.tgztar -zxvf mongodb-linux-x86_64-subscription-ubuntu1204-2.4.9.tgzcp -R -n mongodb-linux-x86_64-subscription-ubuntu1204-2.4.9/ mongodb

    Red Hat Enterprise Linux 6.x

    10http://www.gnu.org/software/gsasl/11http://www.gnu.org/software/gsasl/12http://www.mongodb.com/products/mongodb-enterprise

    1.1. Installation Guides 17

  • MongoDB Documentation, Release 2.4.9

    curl -O http://downloads.10gen.com/linux/mongodb-linux-x86_64-subscription-rhel62-2.4.9.tgztar -zxvf mongodb-linux-x86_64-subscription-rhel62-2.4.9.tgzcp -R -n mongodb-linux-x86_64-subscription-rhel62-2.4.9/ mongodb

    Amazon Linux AMIcurl -O http://downloads.10gen.com/linux/mongodb-linux-x86_64-subscription-amzn64-2.4.9.tgztar -zxvf mongodb-linux-x86_64-subscription-amzn64-2.4.9.tgzcp -R -n mongodb-linux-x86_64-subscription-amzn64-2.4.9/ mongodb

    SUSE Enterprise Linuxcurl -O http://downloads.10gen.com/linux/mongodb-linux-x86_64-subscription-suse11-2.4.9.tgztar -zxvf mongodb-linux-x86_64-subscription-suse11-2.4.9.tgzcp -R -n mongodb-linux-x86_64-subscription-suse11-2.4.9/ mongodb

    Running and Using MongoDB

    Note: The Enterprise packages currently include an example SNMP configuration file named mongod.conf. Thisfile is not a MongoDB configuration file.

    Before you start mongod for the first 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/db

    Step 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/db

    You must create the mongodb user separately.

    You can specify an alternate path for data files 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 system prompt.

    For example, if your PATH includes the location of the mongod binary, enter mongod at the system prompt.

    mongod

    If 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

    Whether using the default /data/db or an alternate directory, ensure that the user account running mongod has readand write permissions to the directory.

    18 Chapter 1. Install MongoDB

  • MongoDB Documentation, Release 2.4.9

    Stop MongoDB To stop the mongod instance, press Control+C in the terminal where the mongod instance isrunning.

    Further Reading

    As you begin to use MongoDB, consider the Getting Started with MongoDB (page 19) and MongoDB Tutorials(page 187) resources. To read about features only available in MongoDB Enterprise, consider: Monitor MongoDBwith SNMP (page 178) and Deploy MongoDB with Kerberos Authentication (page 261).

    1.2 First Steps with MongoDB

    After 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 24) To support initial exploration, generate test data to facilitate testing.

    1.2.1 Getting Started with MongoDB

    This tutorial addresses the following aspects of MongoDB use:

    Connect to a Database (page 19) Connect to a mongod (page 20) 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 22) Use Array Operations with the Cursor (page 22) Query for Specific Documents (page 23) Return a Single Document from a Collection (page 23) Limit the Number of Documents in the Result Set (page 23)

    Next Steps with MongoDB (page 24)

    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 API13

    documentation and the mongo shell JavaScript Method Reference.

    The tutorial assumes that youre running MongoDB on a Linux or OS X operating system and 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 Database

    In 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.

    13http://api.mongodb.org/js

    1.2. First Steps with MongoDB 19

  • MongoDB Documentation, Release 2.4.9

    Connect to a mongod

    From a system prompt, start mongo by issuing the mongo command, as follows:

    mongo

    By 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.

    Select a Database

    After 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:

    db

    1. From the mongo shell, display the list of databases, with the following operation:

    show dbs

    2. Switch to a new database named mydb, with the following operation:

    use mydb

    3. Confirm 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:

    db

    At 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 Help

    At any point, you can access help for the mongo shell using the following operation:

    help

    Furthermore, 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 Documents

    In this section, you insert documents into a new collection named testData within the new database named mydb.

    MongoDB will create a collection implicitly upon its first use. You do not need to create a collection before insertingdata. Furthermore, because MongoDB uses dynamic schemas (page 558), you also need not specify the structure ofyour documents before inserting them into the collection.

    1. From the mongo shell, confirm you are in the mydb database by issuing the following:

    db

    20 Chapter 1. Install MongoDB

  • MongoDB Documentation, Release 2.4.9

    2. If mongo does not return mydb for the previous operation, set the context to the mydb database, with thefollowing operation:

    use mydb

    3. 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:

    db.testData.insert( j )db.testData.insert( k )

    When you insert the first document, the mongod will create both the mydb database and the testDatacollection.

    5. Confirm that the testData collection exists. Issue the following operation:

    show collections

    The 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 227) collection.

    6. Confirm 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 field with a unique value. These operations do not explicitlyspecify a value for the _id field, so mongo creates a unique ObjectId (page 129) value for the field beforeinserting it into the collection.

    Insert Documents using a For Loop or a JavaScript Function

    To perform the remaining procedures in this tutorial, first add more documents to your database using one or both ofthe procedures described in Generate Test Data (page 24).

    Working with the Cursor

    When 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 first 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.

    1.2. First Steps with MongoDB 21

  • MongoDB Documentation, Release 2.4.9

    Iterate over the Cursor with a Loop

    Before using this procedure, make sure to add at least 25 documents to a collection using one of the procedures inGenerate Test Data (page 24). 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:

    while ( 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 field named x, the operationdisplays the field as well as each documents 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 Cursor

    The 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 find the document at the array index 4, use the following operation:

    printjson( c [ 4 ] )

    MongoDB returns the following:

    { "_id" : ObjectId("51a7dc7b2cacf40b79990bea"), "x" : 5 }

    22 Chapter 1. Install MongoDB

  • MongoDB Documentation, Release 2.4.9

    When you access documents in a cursor using the array index notation, mongo first 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 Specific Documents

    MongoDB has a rich query system that allows you to select and filter the documents in a collection along specificfields and values. See Query Documents (page 60) and Read Operations (page 31) for a full account of queries inMongoDB.

    In this procedure, you query for specific documents in the testData collection by passing a query document as aparameter to the find() method. A query document specifies the criteria the query must match to return a document.

    In the mongo shell, query for all documents where the x field 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 fits this criteria:

    { "_id" : ObjectId("51a7dc7b2cacf40b79990bf7"), "x" : 18 }

    Return a Single Document from a Collection

    With 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 from the 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 Set

    To 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 }

    1.2. First Steps with MongoDB 23

  • MongoDB Documentation, Release 2.4.9

    Next Steps with MongoDB

    For 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 Data

    This tutorial describes how to quickly generate test data as you need to test basic MongoDB operations.

    Insert Multiple Documents Using a For Loop

    You can add documents to a new or existing collection by using a JavaScript for loop run from the 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

  • MongoDB Documentation, Release 2.4.9

    { "_id" : ObjectId("51a7dce92cacf40b79990bff"), "x" : 24 }{ "_id" : ObjectId("51a7dce92cacf40b79990c00"), "x" : 25 }

    Insert Multiple Documents with a mongo Shell Function

    You 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});

    }

    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 field 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 file. 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 them implicitly before inserting documents.

    See also:

    MongoDB CRUD Concepts (page 29) and Data Models (page 97).

    1.2. First Steps with MongoDB 25

  • MongoDB Documentation, Release 2.4.9

    26 Chapter 1. Install MongoDB

  • CHAPTER 2

    MongoDB CRUD Operations

    MongoDB 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 modification operations.

    MongoDB CRUD Reference (page 82) Reference material for the query and data manipulation interfaces.

    2.1 MongoDB CRUD Introduction

    MongoDB stores data in the form of documents, which are JSON-like field 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, MongoDB documents 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.

    27

  • MongoDB Documentation, Release 2.4.9

    Figure 2.2: A collection of MongoDB documents.

    2.1.1 Database Operations

    Query

    In MongoDB a query targets a specific collection of documents. Queries specify criteria, or conditions, that identifythe documents that MongoDB returns to the clients. A query may include a projection that specifies the fields fromthe matching documents to return. You can optionally modify queries to impose limits, skips, and sort orders.

    In the following diagram, the query process specifies a query criteria and a sort modifier:

    Data Modification

    Data modification 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 Features

    Indexes

    To enhance the performance of common queries and updates, MongoDB has full support for secondary indexes. Theseindexes allow applications to store a view of a portion of the collection in an efficient data structure. Most indexes storean ordered representation of all values of a field or a group of fields. 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 Operations

  • MongoDB Documentation, Release 2.4.9

    Figure 2.3: The stages of a MongoDB query with a query criteria and a sort modifier.

    Read Preference

    For 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 Concern

    Applications 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.

    Aggregation

    In 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 field, orprocess a collection of documents using a versatile stage-based data processing pipeline or map-reduce operations.

    2.2 MongoDB CRUD Concepts

    The 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 queryspecifications.

    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 29

  • MongoDB Documentation, Release 2.4.9

    Figure 2.4: The stages of a MongoDB insert operation.

    30 Chapter 2. MongoDB CRUD Operations

  • MongoDB Documentation, Release 2.4.9

    Distributed 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 how MongoDB directs write operations on sharded clustersand replica sets and the performance characteristics of these operations.

    2.2.1 Read Operations

    Read operations, or queries, retrieve data stored in the database. In MongoDB, queries select documents from a singlecollection.

    Queries specify criteria, or conditions, that identify the documents that MongoDB returns to the clients. A query mayinclude a projection that specifies the fields from the matching documents to return. The projection limits the amountof data that MongoDB returns to the client over the network.

    Query Interface

    For 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 diagram highlights the components of a MongoDB query operation:

    Figure 2.5: The components of a MongoDB find operation.

    The next diagram shows the same query in SQL:

    Figure 2.6: The components of a SQL SELECT statement.

    Example

    2.2. MongoDB CRUD Concepts 31

  • MongoDB Documentation, Release 2.4.9

    db.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 fields. See Projections (page 32) for details.

    SeeSQL to MongoDB Mapping Chart (page 85) for additional examples of MongoDB queries and the corresponding SQLstatements.

    Query Behavior

    MongoDB 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 defined and is not defined unless you specify a sort().

    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 Statements

    Consider the following diagram of the query process that specifies a query criteria and a sort modifier:

    In the diagram, the query selects documents from the users collection. Using a query selection operatorto define the conditions for matching documents, the query selects documents that have age greater than (i.e. $gt)18. Then the sort() modifier sorts the results by age in ascending order.

    For additional examples of queries, see Query Documents (page 60).

    Projections

    Queries in MongoDB return all fields 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 fields, applicationsreduce their network overhead and processing requirements.

    Projections, which are the the second argument to the find() method, may either specify a list of fields to return orlist fields to exclude in the result documents.

    Important: Except for excluding the _id field in inclusive projections, you cannot mix exclusive and inclusiveprojections.

    Consider the following diagram of the query process that specifies a query criteria and a projection:

    In the diagram, the query selects from the users collection. The criteria matches the documents that have age equalto 18. Then the projection specifies that only the name field should return in the matching documents.

    32 Chapter 2. MongoDB CRUD Operations

  • MongoDB Documentation, Release 2.4.9

    Figure 2.7: The stages of a MongoDB query with a query criteria and a sort modifier.

    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 33

  • MongoDB Documentation, Release 2.4.9

    Projection Examples

    Exclude One Field From a 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 field.

    Return Two fields 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 field (implicitly included) as well as the name and emailfields.

    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 fields.

    SeeLimit Fields to Return from a Query (page 63) for more examples of queries with projection statements.

    Projection Behavior

    MongoDB projections have the following properties:

    In MongoDB, the _id field is always included in results unless explicitly excluded.

    For fields 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 Concepts

    The 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 efficiently aspossible.

    Distributed Queries (page 38) Describes how sharded clusters and replica sets affect the performance of read opera-tions.

    34 Chapter 2. MongoDB CRUD Operations

  • MongoDB Documentation, Release 2.4.9

    Cursors

    In 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 times 1 to print up tothe first 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 first 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 Behaviors

    Closure 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 flag2

    in your query; however, you should either close the cursor manually or exhaust the cursor. In the mongo shell, youcan set the noTimeout flag:

    var myCursor = db.inventory.find().addOption(DBQuery.Option.noTimeout);

    See your driver (page 95) documentation for information on setting the noTimeout flag. For the mongo shell, seecursor.addOption() for a complete list of available cursor flags.

    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 568).

    Cursor Batches The MongoDB server returns the query results in batches. Batch size will not exceed the maximumBSON document size. For most queries, the first 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 first 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();

    1 You can use the DBQuery.shellBatchSize to change the number of iteration from the default value 20. See Executing Queries(page 213) for more information.

    2http://docs.mongodb.org/meta-driver/latest/legacy/mongodb-wire-protocol

    2.2. MongoDB CRUD Concepts 35

  • MongoDB Documentation, Release 2.4.9

    Cursor 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 restart

    Consider the following example:

    db.runCommand( { cursorInfo: 1 } )

    The result from the command returns the following document:

    {"totalOpen" : ,"clientCursors_size" : ,"timedOut" : ,"ok" : 1

    }

    Query Optimization

    Indexes improve the efficiency of read operations by reducing the amount of data that query operations need to process.This simplifies the work associated with fulfilling queries within MongoDB.

    Create an Index to Support Read Operations If your application queries a collection on a particular field or fields,then an index on the queried field or fields can prevent the query from scanning the whole collection to find 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 field. The value of the type field is user-driven.

    var typeValue = ;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 field. 3 In 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 from scanning 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 efficient storageutilization. See db.collection.ensureIndex() and Indexing Tutorials (page 339) for more information aboutindex creation.

    3 For single-field 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 Operations

  • MongoDB Documentation, Release 2.4.9

    Query 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 perform no 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 fields in the query (page 60) are part of that index, and

    all the fields 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 efficientthan inspecting entire documents.

    ExampleGiven a collection inventory with the following index on the type and item fields:

    { type: 1, item: 1 }

    This index will cover the following query on the type and item fields, which returns only the item field:

    db.inventory.find( { type: "food", item:/^c/ },{ item: 1, _id: 0 } )

    However, the index will not cover the following query, which returns the item field and the _id field:

    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 Plans

    The MongoDB query optimizer processes queries and chooses the most efficient query plan for a query given the avail-able indexes. The query system then 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 37

  • MongoDB Documentation, Release 2.4.9

    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 specified 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 Queries

    Read 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 481) 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 efficient when directed to a specific shard. Queries to sharded collectionsshould include the collections shard key (page 494). When a query includes a shard key, the mongos can use clustermetadata from the config database (page 490) 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 inefficient. 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 498) andShard Keys (page 494) 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 sets primary. Youcan modify that behavior by changing the read preference mode (page 477).

    You can configure the read preference mode (page 477) on a per-connection or per-operation basis to allow reads fromsecondaries to:

    38 Chapter 2. MongoDB CRUD Operations

  • MongoDB Documentation, Release 2.4.9

    Figure 2.9: Diagram of a sharded cluster.

    2.2. MongoDB CRUD Concepts 39

  • MongoDB Documentation, Release 2.4.9

    Figure 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 Operations

  • MongoDB Documentation, Release 2.4.9

    Figure 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 41

  • MongoDB Documentation, Release 2.4.9

    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 from secondary members of replica sets are not guaranteed to reflect the current state of the primary,and the state of secondaries will trail the primary by some amount of time. Often, applications dont 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 477).

    2.2.2 Write Operations

    A write operation is any operation that creates or modifies 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 new data 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 modification operations, MongoDB allows applications to determine the level of acknowledgmentreturned from the database. See Write Concern (page 46).

    42 Chapter 2. MongoDB CRUD Operations

  • MongoDB Documentation, Release 2.4.9

    Create

    Create operations add new documents to a collection. In MongoDB, the db.collection.insert() methodperforms create operations.

    The following diagram highlights the components of a MongoDB insert operation:

    Figure 2.13: The components of a MongoDB insert operations.

    The following diagram shows the same query in SQL:

    Figure 2.14: The components of a SQL INSERT statement.

    ExampleThe following operation inserts a new documents into the users collection. The new document has four fields name,age, and status, and an _id field. MongoDB always adds the _id field to the new document if that field 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 fields: name, age,status, and an _id field. MongoDB always adds the _id field to a new document if the field does not exist.

    For more information, see db.collection.insert() and Insert Documents (page 59).

    2.2. MongoDB CRUD Concepts 43

  • MongoDB Documentation, Release 2.4.9

    Some updates also create records. If an update operation specifies the upsert flag 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 Behavior

    If you add a new document without the _id field, the client library or the mongod instance adds an _id field andpopulates the field with a unique ObjectId.

    If you specify the _id field, 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.

    Update

    Update operations modify existing documents in a collection. In MongoDB, db.collection.update() andthe db.collection.save() methods perform update operations. The db.collection.update() methodcan accept 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 diagram highlights the components of a MongoDB update operation:

    Figure 2.15: The components of a MongoDB update operation.

    The following diagram shows the same query in SQL:

    Figure 2.16: The components of a SQL UPDATE statement.

    44 Chapter 2. MongoDB CRUD Operations

  • MongoDB Documentation, Release 2.4.9

    Exampledb.users.update(

    { age: { $gt: 18 } },{ $set: { status: "A" } },{ multi: true }

    )

    This update operation on the users collection sets the status field 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 Behavior

    By default, the db.collection.update()method updates a single document. However, with the multi option,update() can update all documents in a collection that match a query.

    The db.collection.update() method either updates specific fields 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 fields 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 information

    Delete

    Delete operations remove documents from a collection. In MongoDB, db.collection.remove() method per-forms delete operations. The db.collection.remove() method can accept query criteria to determine whichdocuments to remove.

    The following diagram highlights the components of a MongoDB remove operation:

    Figure 2.17: The components of a MongoDB remove operation.

    The following diagram shows the same query in SQL:

    Exampledb.users.remove(

    { status: "D" })

    2.2. MongoDB CRUD Concepts 45

  • MongoDB Documentation, Release 2.4.9

    Figure 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 Behavior

    By default, db.collection.remove() method removes all documents that match its query. However, themethod can accept a flag to limit the delete operation to a single document.

    Isolation of Write Operations

    The modification of a single document is always atomic, even if t