0% found this document useful (0 votes)
376 views955 pages

MongoDB Reference Manual Master

ddddddddddddd

Uploaded by

larbi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
376 views955 pages

MongoDB Reference Manual Master

ddddddddddddd

Uploaded by

larbi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MongoDB Reference Manual

Release 3.0.7

MongoDB, Inc.

October 24, 2015


2
MongoDB, Inc. 2008 - 2015 This work is licensed under a Creative Commons Attribution-NonCommercial-
ShareAlike 3.0 United States License

3
Contents

1 About MongoDB Documentation 3


1.1 License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Editions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Version and Revisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Report an Issue or Make a Change Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Contribute to the Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 Interfaces Reference 19
2.1 mongo Shell Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2 Database Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
2.3 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
2.4 Aggregation Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581

3 MongoDB and SQL Interface Comparisons 593


3.1 SQL to MongoDB Mapping Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
3.2 SQL to Aggregation Mapping Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599

4 Program and Tool Reference Pages 603


4.1 MongoDB Package Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603

5 Internal Metadata 711


5.1 Config Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711
5.2 The local Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 716
5.3 System Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 718

6 General System Reference 721


6.1 Configuration File Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 721
6.2 MongoDB Server Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749
6.3 MongoDB Limits and Thresholds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
6.4 Explain Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766
6.5 Connection String URI Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
6.6 MongoDB Extended JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
6.7 Log Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 782
6.8 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785

7 Release Notes 797


7.1 Current Stable Release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
7.2 Previous Stable Releases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849
7.3 Other MongoDB Release Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 949

i
ii
MongoDB Reference Manual, Release 3.0.7

This document contains all of the reference material from the MongoDB Manual, reflecting the 3.0.7 release. See
the full manual, for complete documentation of MongoDB, its operation, and use.

Contents 1
MongoDB Reference Manual, Release 3.0.7

2 Contents
CHAPTER 1

About MongoDB Documentation

The MongoDB Manual1 contains comprehensive documentation on MongoDB. This page describes the manuals
licensing, editions, and versions, and describes how to make a change request and how to contribute to the manual.

1.1 License

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License2
MongoDB, Inc. 2008-2015

1.2 Editions

In addition to the MongoDB Manual3 , you can also access this content in the following editions:
PDF Format4 (without reference).
HTML tar.gz5
You also can access PDF files that contain subsets of the MongoDB Manual:
MongoDB Reference Manual6
MongoDB CRUD Operations7
Data Models for MongoDB8
MongoDB Data Aggregation9
Replication and MongoDB10
Sharding and MongoDB11
1 [Link]
2 [Link]
3 [Link]
4 [Link]
5 [Link]
6 [Link]
7 [Link]
8 [Link]
9 [Link]
10 [Link]
11 [Link]

3
MongoDB Reference Manual, Release 3.0.7

MongoDB Administration12
MongoDB Security13
MongoDB Reference documentation is also available as part of dash14 . You can also access the MongoDB Man
Pages15 which are also distributed with the official MongoDB Packages.

1.3 Version and Revisions

This version of the manual reflects version 3.0 of MongoDB.


See the MongoDB Documentation Project Page16 for an overview of all editions and output formats of the MongoDB
Manual. You can see the full revision history and track ongoing improvements and additions for all versions of the
manual from its GitHub repository17 .
This edition reflects master branch of the documentation as of the
a27e57257314c60d2baf91b1b0a6761ace673916 revision. This branch is explicitly accessible via
[Link] and you can always reference the commit of the current manual in the release.txt18
file.
The most up-to-date, current, and stable version of the manual is always available at
[Link]

1.4 Report an Issue or Make a Change Request

To report an issue with this manual or to make a change request, file a ticket at the MongoDB DOCS Project on Jira19 .

1.5 Contribute to the Documentation

1.5.1 MongoDB Manual Translation

The original language of all MongoDB documentation is American English. However it is of critical importance to
the documentation project to ensure that speakers of other languages can read and understand the documentation.
To this end, the MongoDB Documentation Project is preparing to launch a translation effort to allow the community
to help bring the documentation to speakers of other languages.
If you would like to express interest in helping to translate the MongoDB documentation once this project is opened
to the public, please:
complete the MongoDB Contributor Agreement20 , and
join the mongodb-translators21 user group.
12 [Link]
13 [Link]
14 [Link]
15 [Link]
16 [Link]
17 [Link]
18 [Link]
19 [Link]
20 [Link]
21 [Link]

4 Chapter 1. About MongoDB Documentation


MongoDB Reference Manual, Release 3.0.7

The mongodb-translators22 user group exists to facilitate collaboration between translators and the documentation
team at large. You can join the group without signing the Contributor Agreement, but you will not be allowed to
contribute translations.
See also:
Contribute to the Documentation (page 4)
Style Guide and Documentation Conventions (page 5)
MongoDB Manual Organization (page 14)
MongoDB Documentation Practices and Processes (page 11)
MongoDB Documentation Build System (page 15)
The entire documentation source for this manual is available in the mongodb/docs repository23 , which is one of the
MongoDB project repositories on GitHub24 .
To contribute to the documentation, you can open a GitHub account25 , fork the mongodb/docs repository26 , make a
change, and issue a pull request.
In order for the documentation team to accept your change, you must complete the MongoDB Contributor Agree-
ment27 .
You can clone the repository by issuing the following command at your system shell:
git clone git://[Link]/mongodb/[Link]

1.5.2 About the Documentation Process

The MongoDB Manual uses Sphinx28 , a sophisticated documentation engine built upon Python Docutils29 . The orig-
inal reStructured Text30 files, as well as all necessary Sphinx extensions and build tools, are available in the same
repository as the documentation.
For more information on the MongoDB documentation process, see:

Style Guide and Documentation Conventions

This document provides an overview of the style for the MongoDB documentation stored in this repository. The
overarching goal of this style guide is to provide an accessible base style to ensure that our documentation is easy to
read, simple to use, and straightforward to maintain.
For information regarding the MongoDB Manual organization, see MongoDB Manual Organization (page 14).

Document History

2011-09-27: Document created with a (very) rough list of style guidelines, conventions, and questions.
22 [Link]
23 [Link]
24 [Link]
25 [Link]
26 [Link]
27 [Link]
28 [Link]
29 [Link]
30 [Link]

1.5. Contribute to the Documentation 5


MongoDB Reference Manual, Release 3.0.7

2012-01-12: Document revised based on slight shifts in practice, and as part of an effort of making it easier for people
outside of the documentation team to contribute to documentation.
2012-03-21: Merged in content from the Jargon, and cleaned up style in light of recent experiences.
2012-08-10: Addition to the Referencing section.
2013-02-07: Migrated this document to the manual. Added map-reduce terminology convention. Other edits.
2013-11-15: Added new table of preferred terms.

Naming Conventions

This section contains guidelines on naming files, sections, documents and other document elements.
File naming Convention:
For Sphinx, all files should have a .txt extension.
Separate words in file names with hyphens (i.e. -.)
For most documents, file names should have a terse one or two word name that de-
scribes the material covered in the document. Allow the path of the file within the doc-
ument tree to add some of the required context/categorization. For example its accept-
able to have [Link] and
[Link]
For tutorials, the full title of the document should be in the file name. For example,
[Link]
Phrase headlines and titles so users can determine what questions the text will answer, and material that will
be addressed, without needing them to read the content. This shortens the amount of time that people spend
looking for answers, and improvise search/scanning, and possibly SEO.
Prefer titles and headers in the form of Using foo over How to Foo.
When using target references (i.e. :ref: references in documents), use names that include enough context to
be intelligible through all documentation. For example, use replica-set-secondary-only-node as
opposed to secondary-only-node. This makes the source more usable and easier to maintain.

Style Guide

This includes the local typesetting, English, grammatical, conventions and preferences that all documents in the manual
should use. The goal here is to choose good standards, that are clear, and have a stylistic minimalism that does not
interfere with or distract from the content. A uniform style will improve user experience and minimize the effect of a
multi-authored document.

Punctuation
Use the Oxford comma.
Oxford commas are the commas in a list of things (e.g. something, something else, and another thing) before
the conjunction (e.g. and or or.).
Do not add two spaces after terminal punctuation, such as periods.
Place commas and periods inside quotation marks.

6 Chapter 1. About MongoDB Documentation


MongoDB Reference Manual, Release 3.0.7

Headings Use title case for headings and document titles. Title case capitalizes the first letter of the first, last, and
all significant words.

Verbs Verb tense and mood preferences, with examples:


Avoid the first person. For example do not say, We will begin the backup process by locking the database, or
I begin the backup process by locking my database instance.
Use the second person. If you need to back up your database, start by locking the database first. In practice,
however, its more concise to imply second person using the imperative, as in Before initiating a backup, lock
the database.
When indicated, use the imperative mood. For example: Backup your databases often and To prevent data
loss, back up your databases.
The future perfect is also useful in some cases. For example, Creating disk snapshots without locking the
database will lead to an invalid state.
Avoid helper verbs, as possible, to increase clarity and concision. For example, attempt to avoid this does
foo and this will do foo when possible. Use does foo over will do foo in situations where this foos is
unacceptable.

Referencing
To refer to future or planned functionality in MongoDB or a driver, always link to the Jira case. The Manuals
[Link] provides an :issue: role that links directly to a Jira case (e.g. :issue:\SERVER-9001\).
For non-object references (i.e. functions, operators, methods, database commands, settings) always reference
only the first occurrence of the reference in a section. You should always reference objects, except in section
headings.
Structure references with the why first; the link second.
For example, instead of this:
Use the [Link]
procedure if you have an existing replica set.
Type this:
To deploy a sharded cluster for an existing replica set, see [Link]

General Formulations
Contractions are acceptable insofar as they are necessary to increase readability and flow. Avoid otherwise.
Make lists grammatically correct.
Do not use a period after every item unless the list item completes the unfinished sentence before the list.
Use appropriate commas and conjunctions in the list items.
Typically begin a bulleted list with an introductory sentence or clause, with a colon or comma.
The following terms are one word:
standalone
workflow
Use unavailable, offline, or unreachable to refer to a mongod instance that cannot be accessed. Do not
use the colloquialism down.

1.5. Contribute to the Documentation 7


MongoDB Reference Manual, Release 3.0.7

Always write out units (e.g. megabytes) rather than using abbreviations (e.g. MB.)

Structural Formulations
There should be at least two headings at every nesting level. Within an h2 block, there should be either: no
h3 blocks, 2 h3 blocks, or more than 2 h3 blocks.
Section headers are in title case (capitalize first, last, and all important words) and should effectively describe
the contents of the section. In a single document you should strive to have section titles that are not redundant
and grammatically consistent with each other.
Use paragraphs and paragraph breaks to increase clarity and flow. Avoid burying critical information in the
middle of long paragraphs. Err on the side of shorter paragraphs.
Prefer shorter sentences to longer sentences. Use complex formations only as a last resort, if at all (e.g. com-
pound complex structures that require semi-colons).
Avoid paragraphs that consist of single sentences as they often represent a sentence that has unintentionally
become too complex or incomplete. However, sometimes such paragraphs are useful for emphasis, summary,
or introductions.
As a corollary, most sections should have multiple paragraphs.
For longer lists and more complex lists, use bulleted items rather than integrating them inline into a sentence.
Do not expect that the content of any example (inline or blocked) will be self explanatory. Even when it feels
redundant, make sure that the function and use of every example is clearly described.

ReStructured Text and Typesetting


Place spaces between nested parentheticals and elements in JavaScript examples. For example, prefer { [ a,
a, a ] } over {[a,a,a]}.
For underlines associated with headers in RST, use:
= for heading level 1 or h1s. Use underlines and overlines for document titles.
- for heading level 2 or h2s.
~ for heading level 3 or h3s.
for heading level 4 or h4s.
Use hyphens (-) to indicate items of an ordered list.
Place footnotes and other references, if you use them, at the end of a section rather than the end of a file.
Use the footnote format that includes automatic numbering and a target name for ease of use. For instance a
footnote tag may look like: [#note]_ with the corresponding directive holding the body of the footnote that
resembles the following: .. [#note].
Do not include .. code-block:: [language] in footnotes.
As it makes sense, use the .. code-block:: [language] form to insert literal blocks into the text.
While the double colon, ::, is functional, the .. code-block:: [language] form makes the source
easier to read and understand.
For all mentions of referenced types (i.e. commands, operators, expressions, functions, statuses, etc.) use the
reference types to ensure uniform formatting and cross-referencing.

8 Chapter 1. About MongoDB Documentation


MongoDB Reference Manual, Release 3.0.7

1.5. Contribute to the Documentation 9


MongoDB Reference Manual, Release 3.0.7

Jargon and Common Terms

Pre- Concept Dispreferred Notes


ferred Alternatives
Term
docu- A single, top-level object/record record, object, Prefer document over object because of
ment in a MongoDB collection. row concerns about cross-driver language handling
of objects. Reserve record for allocation of
storage. Avoid row, as possible.
databaseA group of collections. Refers to Avoid genericizing database. Avoid using
a group of data files. This is the database to refer to a server process or a data
logical sense of the term set. This applies both to the datastoring
database. contexts as well as other (related) operational
contexts (command context,
authentication/authorization context.)
in- A daemon process. (e.g. mongos process Avoid using instance, unless it modifies
stance or mongod) (acceptable something specifically. Having a descriptor for
sometimes), node a process/instance makes it possible to avoid
(never needing to make mongod or mongos plural.
acceptable), Server and node are both vague and
server. contextually difficult to disambiguate with
regards to application servers, and underlying
hardware.
field The identifier of a value in a key, column Avoid introducing unrelated terms for a single
name document. field. In the documentation weve rarely had to
discuss the identifier of a field, so the extra
word here isnt burdensome.
The name/value pair that
field/value key, slot, attribute Use to emphasize the difference between the
describes a unit of data in name of a field and its value For example,
MongoDB. _id is the field and the default value is an
ObjectId.
value The data content of a field. data
Mon- A group of processes, or mongo, Stylistic preference, mostly. In some cases its
goDB deployment that implement the mongodb, cluster useful to be able to refer generically to
MongoDB interface. instances (that may be either mongod or
mongos.)
em- An embedded or nested embedded
bed- document within a document or document, nested
ded an array. document
docu-
ment
map- An operation performed by the mapReduce, map Avoid confusion with the command, shell
reduce mapReduce command. reduce, helper, and driver interfaces. Makes it possible
map/reduce to discuss the operation generally.
clus- A sharded cluster. grid, shard Cluster is a great word for a group of
ter cluster, set, processes; however, its important to avoid
deployment letting the term become generic. Do not use for
any group of MongoDB processes or
deployments.
sharded A sharded cluster. shard cluster,
clus- cluster, sharded
ter system
replica A deployment of replicating set, replication
set mongod programs that provide deployment
redundancy and automatic
10 failover. Chapter 1. About MongoDB Documentation
de- A group of MongoDB processes, cluster, system Typically in the form MongoDB deployment.
ploy- or a standalone mongod Includes standalones, replica sets and sharded
ment instance. clusters.
MongoDB Reference Manual, Release 3.0.7

Database Systems and Processes


To indicate the entire database system, use MongoDB, not mongo or Mongo.
To indicate the database process or a server instance, use mongod or mongos. Refer to these as processes
or instances. Reserve database for referring to a database structure, i.e., the structure that holds collections
and refers to a group of files on disk.

Distributed System Terms


Refer to partitioned systems as sharded clusters. Do not use shard clusters or sharded systems.
Refer to configurations that run with replication as replica sets (or master/slave deployments) rather than
clusters or other variants.

Data Structure Terms


document refers to rows or records in a MongoDB database. Potential confusion with JSON Docu-
ments.
Do not refer to documents as objects, because drivers (and MongoDB) do not preserve the order of fields when
fetching data. If the order of objects matter, use an array.
field refers to a key or identifier of data within a MongoDB document.
value refers to the contents of a field.
embedded document describes a nested document.

Other Terms
Use [Link] (and .org or .com if needed) for all examples and samples.
Hyphenate map-reduce in order to avoid ambiguous reference to the command name. Do not camel-case.

Notes on Specific Features

Geo-Location
1. While MongoDB is capable of storing coordinates in embedded documents, in practice, users should only
store coordinates in arrays. (See: DOCS-4131 .)

MongoDB Documentation Practices and Processes

This document provides an overview of the practices and processes.

Commits

When relevant, include a Jira case identifier in a commit message. Reference documentation cases when applicable,
but feel free to reference other cases from [Link].org32 .
Err on the side of creating a larger number of discrete commits rather than bundling large set of changes into one
commit.
31 [Link]
32 [Link]

1.5. Contribute to the Documentation 11


MongoDB Reference Manual, Release 3.0.7

For the sake of consistency, remove trailing whitespaces in the source file.
Hard wrap files to between 72 and 80 characters per-line.

Standards and Practices

At least two people should vet all non-trivial changes to the documentation before publication. One of the
reviewers should have significant technical experience with the material covered in the documentation.
All development and editorial work should transpire on GitHub branches or forks that editors can then merge
into the publication branches.

Collaboration

To propose a change to the documentation, do either of the following:


Open a ticket in the documentation project33 proposing the change. Someone on the documentation team will
make the change and be in contact with you so that you can review the change.
Using GitHub34 , fork the mongodb/docs repository35 , commit your changes, and issue a pull request. Someone
on the documentation team will review and incorporate your change into the documentation.

Builds

Building the documentation is useful because Sphinx36 and docutils can catch numerous errors in the format and
syntax of the documentation. Additionally, having access to an example documentation as it will appear to the users
is useful for providing more effective basis for the review process. Besides Sphinx, Pygments, and Python-Docutils,
the documentation repository contains all requirements for building the documentation resource.
Talk to someone on the documentation team if you are having problems running builds yourself.

Publication

The makefile for this repository contains targets that automate the publication process. Use make html to publish
a test build of the documentation in the build/ directory of your repository. Use make publish to build the full
contents of the manual from the current branch in the ../public-docs/ directory relative the docs repository.
Other targets include:
man - builds UNIX Manual pages for all Mongodb utilities.
push - builds and deploys the contents of the ../public-docs/.
pdfs - builds a PDF version of the manual (requires LaTeX dependencies.)

Branches

This section provides an overview of the git branches in the MongoDB documentation repository and their use.
33 [Link]
34 [Link]
35 [Link]
36 [Link]

12 Chapter 1. About MongoDB Documentation


MongoDB Reference Manual, Release 3.0.7

At the present time, future work transpires in the master, with the main publication being current. As the
documentation stabilizes, the documentation team will begin to maintain branches of the documentation for specific
MongoDB releases.

Migration from Legacy Documentation

The [Link] Wiki contains a wealth of information. As the transition to the Manual (i.e. this project and
resource) continues, its critical that no information disappears or goes missing. The following process outlines how
to migrate a wiki page to the manual:
1. Read the relevant sections of the Manual, and see what the new documentation has to offer on a specific topic.
In this process you should follow cross references and gain an understanding of both the underlying information
and how the parts of the new content relates its constituent parts.
2. Read the wiki page you wish to redirect, and take note of all of the factual assertions, examples presented by the
wiki page.
3. Test the factual assertions of the wiki page to the greatest extent possible. Ensure that example output is accurate.
In the case of commands and reference material, make sure that documented options are accurate.
4. Make corrections to the manual page or pages to reflect any missing pieces of information.
The target of the redirect need not contain every piece of information on the wiki page, if the manual as a
whole does, and relevant section(s) with the information from the wiki page are accessible from the target of the
redirection.
5. As necessary, get these changes reviewed by another writer and/or someone familiar with the area of the infor-
mation in question.
At this point, update the relevant Jira case with the target that youve chosen for the redirect, and make the ticket
unassigned.
6. When someone has reviewed the changes and published those changes to Manual, you, or preferably someone
else on the team, should make a final pass at both pages with fresh eyes and then make the redirect.
Steps 1-5 should ensure that no information is lost in the migration, and that the final review in step 6 should be
trivial to complete.

Review Process

Types of Review The content in the Manual undergoes many types of review, including the following:

Initial Technical Review Review by an engineer familiar with MongoDB and the topic area of the documentation.
This review focuses on technical content, and correctness of the procedures and facts presented, but can improve any
aspect of the documentation that may still be lacking. When both the initial technical review and the content review
are complete, the piece may be published.

Content Review Textual review by another writer to ensure stylistic consistency with the rest of the manual. De-
pending on the content, this may precede or follow the initial technical review. When both the initial technical review
and the content review are complete, the piece may be published.

1.5. Contribute to the Documentation 13


MongoDB Reference Manual, Release 3.0.7

Consistency Review This occurs post-publication and is content focused. The goals of consistency reviews are to
increase the internal consistency of the documentation as a whole. Insert relevant cross-references, update the style as
needed, and provide background fact-checking.
When possible, consistency reviews should be as systematic as possible and we should avoid encouraging stylistic and
information drift by editing only small sections at a time.

Subsequent Technical Review If the documentation needs to be updated following a change in functionality of the
server or following the resolution of a user issue, changes may be significant enough to warrant additional technical
review. These reviews follow the same form as the initial technical review, but is often less involved and covers a
smaller area.

Review Methods If youre not a usual contributor to the documentation and would like to review something, you
can submit reviews in any of the following methods:
If youre reviewing an open pull request in GitHub, the best way to comment is on the overview diff, which
you can find by clicking on the diff button in the upper left portion of the screen. You can also use the
following URL to reach this interface:
[Link]

Replace [pull-request-id] with the identifier of the pull request. Make all comments inline, using
GitHubs comment system.
You may also provide comments directly on commits, or on the pull request itself but these commit-comments
are archived in less coherent ways and generate less useful emails, while comments on the pull request lead to
less specific changes to the document.
Leave feedback on Jira cases in the DOCS37 project. These are better for more general changes that arent
necessarily tied to a specific line, or affect multiple files.
Create a fork of the repository in your GitHub account, make any required changes and then create a pull request
with your changes.
If you insert lines that begin with any of the following annotations:
.. TODO:
TODO:
.. TODO
TODO

followed by your comments, it will be easier for the original writer to locate your comments. The two dots ..
format is a comment in reStructured Text, which will hide your comments from Sphinx and publication if youre
worried about that.
This format is often easier for reviewers with larger portions of content to review.

MongoDB Manual Organization

This document provides an overview of the global organization of the documentation resource. Refer to the notes
below if you are having trouble understanding the reasoning behind a files current location, or if you want to add new
documentation but arent sure how to integrate it into the existing resource.
If you have questions, dont hesitate to open a ticket in the Documentation Jira Project38 or contact the documentation
team39 .
37 [Link]
38 [Link]
39 docs@[Link]

14 Chapter 1. About MongoDB Documentation


MongoDB Reference Manual, Release 3.0.7

Global Organization

Indexes and Experience The documentation project has two index files:
[Link] and [Link]
The contents file provides the documentations tree structure, which Sphinx uses to create the left-pane navigational
structure, to power the Next and Previous page functionality, and to provide all overarching outlines of the
resource. The index file is not included in the contents file (and thus builds will produce a warning here) and is
the page that users first land on when visiting the resource.
Having separate contents and index files provides a bit more flexibility with the organization of the resource while
also making it possible to customize the primary user experience.

Topical Organization The placement of files in the repository depends on the type of documentation rather than the
topic of the content. Like the difference between [Link] and [Link], by decoupling the organization
of the files from the organization of the information the documentation can be more flexible and can more adequately
address changes in the product and in users needs.
Files in the source/ directory represent the tip of a logical tree of documents, while directories are containers of
types of content. The administration and applications directories, however, are legacy artifacts and with a
few exceptions contain sub-navigation pages.
With several exceptions in the reference/ directory, there is only one level of sub-directories in the source/
directory.

Tools

The organization of the site, like all Sphinx sites derives from the toctree40 structure. However, in order to annotate
the table of contents and provide additional flexibility, the MongoDB documentation generates toctree41 structures
using data from YAML files stored in the source/includes/ directory. These files start with ref-toc or toc
and generate output in the source/includes/toc/ directory. Briefly this system has the following behavior:
files that start with ref-toc refer to the documentation of API objects (i.e. commands, operators and methods),
and the build system generates files that hold toctree42 directives as well as files that hold tables that list
objects and a brief description.
files that start with toc refer to all other documentation and the build system generates files that hold
toctree43 directives as well as files that hold definition lists that contain links to the documents and short
descriptions the content.
file names that have spec following toc or ref-toc will generate aggregated tables or definition lists and
allow ad-hoc combinations of documents for landing pages and quick reference guides.

MongoDB Documentation Build System

This document contains more direct instructions for building the MongoDB documentation.

Getting Started

Install Dependencies The MongoDB Documentation project depends on the following tools:
40 [Link]
41 [Link]
42 [Link]
43 [Link]

1.5. Contribute to the Documentation 15


MongoDB Reference Manual, Release 3.0.7

Python
Git
Inkscape (Image generation.)
LaTeX/PDF LaTeX (typically texlive; for building PDFs)
Giza44

OS X Install Sphinx, Docutils, and their dependencies with easy_install the following command:
easy_install giza

Feel free to use pip rather than easy_install to install python packages.
To generate the images used in the documentation, download and install Inkscape45 .

Optional
To generate PDFs for the full production build, install a TeX distribution (for building the PDF.) If you do not have a
LaTeX installation, use MacTeX46 . This is only required to build PDFs.

Arch Linux Install packages from the system repositories with the following command:
pacman -S inkscape python2-pip

Then install the following Python packages:


pip2 install giza

Optional
To generate PDFs for the full production build, install the following packages from the system repository:
pacman -S texlive-bin texlive-core texlive-latexextra

Debian/Ubuntu Install the required system packages with the following command:
apt-get install inkscape python-pip

Then install the following Python packages:


pip install giza

Optional
To generate PDFs for the full production build, install the following packages from the system repository:
apt-get install texlive-latex-recommended texlive-latex-recommended

44 [Link]
45 [Link]
46 [Link]

16 Chapter 1. About MongoDB Documentation


MongoDB Reference Manual, Release 3.0.7

Setup and Configuration Clone the repository:


git clone git://[Link]/mongodb/[Link]

Building the Documentation

The MongoDB documentation build system is entirely accessible via make targets. For example, to build an HTML
version of the documentation issue the following command:
make html

You can find the build output in build/<branch>/html, where <branch> is the name of the current branch.
In addition to the html target, the build system provides the following targets:
publish Builds and integrates all output for the production build. Build output is in
build/public/<branch>/. When you run publish in the master, the build will generate
some output in build/public/.
push; stage Uploads the production build to the production or staging web servers. Depends on publish. Re-
quires access production or staging environment.
push-all; stage-all Uploads the entire content of build/public/ to the web servers. Depends on
publish. Not used in common practice.
push-with-delete; stage-with-delete Modifies the action of push and stage to remove remote file
that dont exist in the local build. Use with caution.
html; latex; dirhtml; epub; texinfo; man; json These are standard targets derived from the default
Sphinx Makefile, with adjusted dependencies. Additionally, for all of these targets you can append -nitpick
to increase Sphinxs verbosity, or -clean to remove all Sphinx build artifacts.
latex performs several additional post-processing steps on .tex output generated by Sphinx. This target will
also compile PDFs using pdflatex.
html and man also generates a .[Link] file of the build outputs for inclusion in the final releases.
If you have any questions, please feel free to open a Jira Case47 .

47 [Link]

1.5. Contribute to the Documentation 17


MongoDB Reference Manual, Release 3.0.7

18 Chapter 1. About MongoDB Documentation


CHAPTER 2

Interfaces Reference

2.1 mongo Shell Methods

JavaScript in MongoDB
Although these methods use JavaScript, most interactions with MongoDB do not use JavaScript but use an
idiomatic driver in the language of the interacting application.

2.1.1 Collection

Collection Methods

Name Description
[Link]() (page 20) Provides access to the aggregation pipeline.
[Link]() (page 23) Wraps count (page 222) to return a count of the number of docum
[Link]() (page 25) Deprecated. Wraps eval (page 262) to copy data between collecti
[Link]() (page 25) Builds an index on a collection.
[Link]() (page 28) Returns the size of the collection. Wraps the size (page 370) field
[Link]() (page 28) Returns an array of documents that have distinct values for the spec
[Link]() (page 30) Removes the specified collection from the database.
[Link]() (page 30) Removes a specified index on a collection.
[Link]() (page 31) Removes all indexes on a collection.
[Link]() (page 31) Deprecated. Use [Link]() (page 25
[Link]() (page 32) Returns information on the query execution of various methods.
[Link]() (page 35) Performs a query on a collection and returns a cursor object.
[Link]() (page 41) Atomically modifies and returns a single document.
[Link]() (page 45) Performs a query and returns a single document.
[Link]() (page 46) Returns an array of documents that describe the existing indexes on
[Link]() (page 47) For collections in sharded clusters, [Link]
[Link]() (page 48) Internal diagnostic method for shard cluster.
[Link]() (page 49) Provides simple data aggregation function. Groups documents in a
[Link]() (page 52) Creates a new document in a collection.
[Link]() (page 55) Reports if a collection is a capped collection.
[Link]() (page 55) Performs map-reduce style data aggregation.
[Link]() (page 63) Rebuilds all existing indexes on a collection.
[Link]() (page 63) Deletes documents from a collection.

19
MongoDB Reference Manual, Release 3.0.7

Table 2.1 continued from pre


Name Description
[Link]() (page 66) Changes the name of a collection.
[Link]() (page 67) Provides a wrapper around an insert() (page 52) and update(
[Link]() (page 69) Reports on the state of a collection. Provides a wrapper around the
[Link]() (page 70) Reports the total size used by the collection in bytes. Provides a wr
[Link]() (page 70) Reports the total size of a collection, including the size of all docum
[Link]() (page 70) Reports the total size used by the indexes on a collection. Provides
[Link]() (page 70) Modifies a document in a collection.
[Link]() (page 78) Performs diagnostic operations on a collection.

[Link]()

New in version 2.2.

Definition
[Link](pipeline, options)
Calculates aggregate values for the data in a collection.
param array pipeline A sequence of data aggregation operations or stages. See the aggregation
pipeline operators (page 498) for details.
Changed in version 2.6: The method can still accept the pipeline stages as separate arguments
instead of as elements in an array; however, if you do not specify the pipeline as an array,
you cannot specify the options parameter.
param document options Optional. Additional options that aggregate() (page 20) passes to
the aggregate (page 219) command.
New in version 2.6: Available only if you specify the pipeline as an array.
The options document can contain the following fields and values:
field boolean explain Optional. Specifies to return the information on the processing of the pipeline.
See Return Information on Aggregation Pipeline Operation (page 22) for an example.
New in version 2.6.
field boolean allowDiskUse Optional. Enables writing to temporary files. When set to true, ag-
gregation operations can write data to the _tmp subdirectory in the dbPath (page 738) direc-
tory. See Perform Large Sort Operation with External Sort (page 22) for an example.
New in version 2.6.
field document cursor Optional. Specifies the initial batch size for the cursor. The value of the
cursor field is a document with the field batchSize. See Specify an Initial Batch Size
(page 22) for syntax and example.
New in version 2.6.

Returns
A cursor to the documents produced by the final stage of the aggregation pipeline operation, or
if you include the explain option, the document that provides details on the processing of the
aggregation operation.
If the pipeline includes the $out (page 516) operator, aggregate() (page 20) returns an
empty cursor. See $out (page 516) for more information.

20 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Changed in version 2.6: The [Link]() (page 20) method returns a


cursor and can return result sets of any size. Previous versions returned all results in a single
document, and the result set was subject to a size limit of 16 megabytes.
Changed in version 2.4: If an error occurs, the aggregate() (page 20) helper throws an exception. In previous
versions, the helper returned a document with the error message and code, and ok status field not equal to 1, same as
the aggregate (page 219) command.
See also:
For more information, see [Link] Ag-
gregation Reference (page 581), [Link]
and aggregate (page 219).

Cursor Behavior In the mongo (page 632) shell, if the cursor returned from the
[Link]() (page 20) is not assigned to a variable using the var key-
word, then the mongo (page 632) shell automatically iterates the cursor up to 20 times. See
[Link] for cursor behavior in the mongo (page 632)
shell and [Link] for handling cursors
in the mongo (page 632) shell.
Cursors returned from aggregation only supports cursor methods that operate on evaluated cursors (i.e. cursors whose
first batch has been retrieved), such as the following methods:
[Link]() (page 85)
[Link]() (page 91)
[Link]() (page 98)
[Link]() (page 84)
[Link]() (page 87)
[Link]() (page 91)
[Link]() (page 86)
[Link]() (page 91)

Examples The examples in this section use the [Link]() (page 20) helper provided in
the 2.6 version of the mongo (page 632) shell.
The following examples use the collection orders that contains the following documents:
{ _id: 1, cust_id: "abc1", ord_date: ISODate("2012-11-02T[Link].102Z"), status: "A", amount: 50 }
{ _id: 2, cust_id: "xyz1", ord_date: ISODate("2013-10-01T[Link].102Z"), status: "A", amount: 100 }
{ _id: 3, cust_id: "xyz1", ord_date: ISODate("2013-10-12T[Link].102Z"), status: "D", amount: 25 }
{ _id: 4, cust_id: "xyz1", ord_date: ISODate("2013-10-11T[Link].102Z"), status: "D", amount: 125 }
{ _id: 5, cust_id: "abc1", ord_date: ISODate("2013-11-12T[Link].102Z"), status: "A", amount: 25 }

Group by and Calculate a Sum The following aggregation operation selects documents with status equal to "A",
groups the matching documents by the cust_id field and calculates the total for each cust_id field from the
sum of the amount field, and sorts the results by the total field in descending order:
[Link]([
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
])

The operation returns a cursor with the following documents:

2.1. mongo Shell Methods 21


MongoDB Reference Manual, Release 3.0.7

{ "_id" : "xyz1", "total" : 100 }


{ "_id" : "abc1", "total" : 75 }

The mongo (page 632) shell iterates the returned cursor automatically to print the results. See
[Link] for handling cursors manually
in the mongo (page 632) shell.

Return Information on Aggregation Pipeline Operation The following aggregation operation sets the option
explain to true to return information about the aggregation operation.
[Link](
[
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
],
{
explain: true
}
)

The operation returns a cursor with the document that contains detailed information regarding the processing of the
aggregation pipeline. For example, the document may show, among other details, which index, if any, the operation
used. 1 If the orders collection is a sharded collection, the document would also show the division of labor between
the shards and the merge operation, and for targeted queries, the targeted shards.

Note: The intended readers of the explain output document are humans, and not machines, and the output format
is subject to change between releases.

The mongo (page 632) shell iterates the returned cursor automatically to print the results. See
[Link] for handling cursors manually
in the mongo (page 632) shell.

Perform Large Sort Operation with External Sort Aggregation pipeline stages have maximum memory use limit.
To handle large datasets, set allowDiskUse option to true to enable writing data to temporary files, as in the
following example:
var results = [Link](
[
{ $project : { cusip: 1, date: 1, price: 1, _id: 0 } },
{ $sort : { cusip : 1, date: 1 } }
],
{
allowDiskUse: true
}
)

Specify an Initial Batch Size To specify an initial batch size for the cursor, use the following syntax for the cursor
option:
cursor: { batchSize: <int> }

For example, the following aggregation operation specifies the initial batch size of 0 for the cursor:
1 index-filters can affect the choice of index used. See index-filters for details.

22 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link](
[
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $limit: 2 }
],
{
cursor: { batchSize: 0 }
}
)

A batchSize of 0 means an empty first batch and is useful for quickly returning a cursor or failure message
without doing significant server-side work. Specify subsequent batch sizes to OP_GET_MORE operations as with
other MongoDB cursors.
The mongo (page 632) shell iterates the returned cursor automatically to print the results. See
[Link] for handling cursors manually
in the mongo (page 632) shell.

[Link]()

Definition
[Link](query)
Returns the count of documents that would match a find() (page 35) query. The
[Link]() (page 23) method does not perform the find() (page 35) operation but
instead counts and returns the number of results that match a query.
The [Link]() (page 23) method has the following parameter:
param document query The query selection criteria.
The [Link]() (page 23) method is equivalent to the
[Link](query).count() construct.
See also:
[Link]() (page 81)

Behavior

Sharded Clusters On a sharded cluster, [Link]() (page 23) can result in an inaccurate count
if orphaned documents exist or if a chunk migration is in progress.
To avoid these situations, on a sharded cluster, use the $group (page 508) stage of the
[Link]() (page 20) method to $sum (page 565) the documents. For example, the
following operation counts the documents in a collection:
[Link](
[
{ $group: { _id: null, count: { $sum: 1 } } }
]
)

To get a count of documents that match a query condition, include the $match (page 501) stage as well:

2.1. mongo Shell Methods 23


MongoDB Reference Manual, Release 3.0.7

[Link](
[
{ $match: <query condition> },
{ $group: { _id: null, count: { $sum: 1 } } }
]
)

See Perform a Count (page 502) for an example.

Index Use Consider a collection with the following index:


{ a: 1, b: 1 }

When performing a count, MongoDB can return the count using only the index if:
the query can use an index,
the query only contains conditions on the keys of the index, and
the query predicates access a single contiguous range of index keys.
For example, the following operations can return the count using only the index:
[Link]( { a: 5, b: 5 } ).count()
[Link]( { a: { $gt: 5 } } ).count()
[Link]( { a: 5, b: { $gt: 10 } } ).count()

If, however, the query can use an index but the query predicates do not access a single contiguous range of index keys
or the query also contains conditions on fields outside the index, then in addition to using the index, MongoDB must
also read the documents to return the count.
[Link]( { a: 5, b: { $in: [ 1, 2, 3 ] } } ).count()
[Link]( { a: { $gt: 5 }, b: 5 } ).count()
[Link]( { a: 5, b: 5, c: 5 } ).count()

In such cases, during the initial read of the documents, MongoDB pages the documents into memory such that subse-
quent calls of the same count operation will have better performance.

Examples

Count all Documents in a Collection To count the number of all documents in the orders collection, use the
following operation:
[Link]()

This operation is equivalent to the following:


[Link]().count()

Count all Documents that Match a Query Count the number of the documents in the orders collection with the
field ord_dt greater than new Date(01/01/2012):
[Link]( { ord_dt: { $gt: new Date('01/01/2012') } } )

The query is equivalent to the following:

24 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link]( { ord_dt: { $gt: new Date('01/01/2012') } } ).count()

[Link]()

Definition
[Link](newCollection)
Deprecated since version 3.0.
Copies all documents from collection into newCollection using server-side JavaScript. If
newCollection does not exist, MongoDB creates it.
If authorization is enabled, you must have access to all actions on all resources in order to run
[Link]() (page 25). Providing such access is not recommended, but if your organi-
zation requires a user to run [Link]() (page 25), create a role that grants anyAction
on resource-anyresource. Do not assign this role to any other user.
param string newCollection The name of the collection to write data to.

Warning: When using [Link]() (page 25) check field types to ensure that the
operation does not remove type information from documents during the translation from BSON to JSON.
The [Link]() (page 25) method uses the eval (page 262) command internally. As
a result, the [Link]() (page 25) operation takes a global lock that blocks all other
read and write operations until the [Link]() (page 25) completes.

copyTo() (page 25) returns the number of documents copied. If the copy fails, it throws an exception.

Behavior Because copyTo() (page 25) uses eval (page 262) internally, the copy operations will block all other
operations on the mongod (page 603) instance.

Example The following operation copies all documents from the source collection into the target collection.
[Link](target)

[Link]()

Definition
[Link](keys, options)
Creates indexes on collections.
param document keys A document that contains the field and value pairs where the field is the
index key and the value describes the type of index for that field. For an ascending index on a
field, specify a value of 1; for descending index, specify a value of -1.
MongoDB supports several different index types including text, geospatial, and hashed
indexes. See [Link] for more
information.
param document options Optional. A document that contains a set of options that controls the
creation of the index. See Options (page 25) for details.

Options The options document contains a set of options that controls the creation of the index. Different index
types can have additional options specific for that type.

2.1. mongo Shell Methods 25


MongoDB Reference Manual, Release 3.0.7

Options for All Index Types The following options are available for all index types unless otherwise specified:
Changed in version 3.0: The dropDups option is no longer available.
param boolean background Optional. Builds the index in the background so that building an index
does not block other database activities. Specify true to build in the background. The default
value is false.
param boolean unique Optional. Creates a unique index so that the collection will not accept insertion
of documents where the index key or keys match an existing value in the index. Specify true to
create a unique index. The default value is false.
The option is unavailable for hashed indexes.
param string name Optional. The name of the index. If unspecified, MongoDB generates an index
name by concatenating the names of the indexed fields and the sort order.
Whether user specified or MongoDB generated, index names including their full namespace (i.e.
[Link]) cannot be longer than the Index Name Limit (page 761).
param boolean sparse Optional. If true, the index only references documents with the specified field.
These indexes use less space but behave differently in some situations (particularly sorts). The de-
fault value is false. See [Link]
for more information.
Changed in version 2.6: 2dsphere indexes are sparse by default and ignore this option. For a
compound index that includes 2dsphere index key(s) along with keys of other types, only the
2dsphere index fields determine whether the index references a document.
2d, geoHaystack, and text indexes behave similarly to the 2dsphere indexes.
param integer expireAfterSeconds Optional. Specifies a value, in seconds, as a
TTL to control how long MongoDB retains documents in this collection. See
[Link] for more infor-
mation on this functionality. This applies only to TTL indexes.
param index version v Optional. The index version number. The default index version depends on the
version of mongod (page 603) running when creating the index. Before version 2.0, the this value
was 0; versions 2.0 and later use version 1, which provides a smaller and faster index format. Specify
a different index version only in unusual situations.
param document storageEngine Optional. Allows users to specify configuration to the storage engine
on a per-index basis when creating an index. The value of the storageEngine option should take
the following form:
{ <storage-engine-name>: <options> }

Storage engine configuration specified when creating indexes are validated and logged to the oplog
during replication to support replica sets with members that use different storage engines.
New in version 3.0.

Options for text Indexes The following options are available for text indexes only:
param document weights Optional. For text indexes, a document that contains field
and weight pairs. The weight is an integer ranging from 1 to 99,999 and de-
notes the significance of the field relative to the other indexed fields in terms of
the score. You can specify weights for some or all the indexed fields. See
[Link]
to adjust the scores. The default value is 1.

26 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

param string default_language Optional. For text indexes, the language


that determines the list of stop words and the rules for the stemmer
and tokenizer. See text-search-languages for the available languages and
[Link]
for more information and examples. The default value is english.
param string language_override Optional. For text indexes, the name of the field, in the collections
documents, that contains the override language for the document. The default value is language.
See specify-language-field-text-index-example for an example.
param integer textIndexVersion Optional. For text indexes, the text index version number. Version
can be either 1 or 2.
In MongoDB 2.6, the default version is 2. MongoDB 2.4 can only support version 1.
New in version 2.6.

Options for 2dsphere Indexes The following option is available for 2dsphere indexes only:
param integer 2dsphereIndexVersion Optional. For 2dsphere indexes, the 2dsphere index ver-
sion number. Version can be either 1 or 2.
In MongoDB 2.6, the default version is 2. MongoDB 2.4 can only support version 1.
New in version 2.6.

Options for 2d Indexes The following options are available for 2d indexes only:
param integer bits Optional. For 2d indexes, the number of precision of the stored geohash value of the
location data.
The bits value ranges from 1 to 32 inclusive. The default value is 26.
param number min Optional. For 2d indexes, the lower inclusive boundary for the longitude and lati-
tude values. The default value is -180.0.
param number max Optional. For 2d indexes, the upper inclusive boundary for the longitude and lati-
tude values. The default value is 180.0.

Options for geoHaystack Indexes The following option is available for geoHaystack indexes only:
param number bucketSize For geoHaystack indexes, specify the number of units within which to
group the location values; i.e. group in the same bucket those location values that are within the
specified number of units to each other.
The value must be greater than 0.

Behaviors The createIndex() (page 25) method has the behaviors described here.
To add or change index options you must drop the index using the dropIndex() (page 30) method and issue
another createIndex() (page 25) operation with the new options.
If you create an index with one set of options, and then issue the createIndex() (page 25) method with the
same index fields and different options without first dropping the index, createIndex() (page 25) will not
rebuild the existing index with the new options.
If you call multiple createIndex() (page 25) methods with the same index specification at the same time,
only the first operation will succeed, all other operations will have no effect.
Non-background indexing operations will block all other operations on a database.

2.1. mongo Shell Methods 27


MongoDB Reference Manual, Release 3.0.7

MongoDB will not create an index (page 25) on a collection if the index entry for an existing document
exceeds the Maximum Index Key Length. Previous versions of MongoDB would create the index but not
index such documents.
Changed in version 2.6.

Examples

Create an Ascending Index on a Single Field The following example creates an ascending index on the field
orderDate.
[Link]( { orderDate: 1 } )

If the keys document specifies more than one field, then createIndex() (page 25) creates a compound index.

Create an Index on a Multiple Fields The following example creates a compound index on the orderDate field
(in ascending order) and the zipcode field (in descending order.)
[Link]( { orderDate: 1, zipcode: -1 } )

A compound index cannot include a hashed index component.

Note: The order of an index is important for supporting sort() (page 94) operations using the index.

Additional Information
Use [Link]() (page 25) rather than [Link]()
(page 31) to create indexes.
The [Link] section of this manual for full documentation of
indexes and indexing in MongoDB.
[Link]() (page 46) to view the specifications of existing indexes for a collection.
[Link] for details on creating text indexes.
index-feature-geospatial and index-geohaystack-index for geospatial queries.
index-feature-ttl for expiration of data.

[Link]()

[Link]()
Returns The size of the collection. This method provides a wrapper around the size (page 370)
output of the collStats (page 369) (i.e. [Link]() (page 69)) com-
mand.

[Link]()

Definition
[Link](field, query)
Finds the distinct values for a specified field across a single collection and returns the results in an array.
param string field The field for which to return distinct values.

28 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

param document query A query that specifies the documents from which to retrieve the distinct
values.
The [Link]() (page 28) method provides a wrapper around the distinct
(page 224) command. Results must not be larger than the maximum BSON size (page 759).

Behavior

Array Fields If the value of the specified field is an array, [Link]() (page 28) consid-
ers each element of the array as a separate value.
For instance, if a field has as its value [ 1, [1], 1 ], then [Link]() (page 28) consid-
ers 1, [1], and 1 as separate values.
For an example, see Return Distinct Values for an Array Field (page 29).

Index Use When possible, [Link]() (page 28) operations can use indexes.
Indexes can also cover [Link]() (page 28) operations. See covered-queries for more infor-
mation on queries covered by indexes.

Examples The examples use the inventory collection that contains the following documents:
{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] }
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }

Return Distinct Values for a Field The following example returns the distinct values for the field dept from all
documents in the inventory collection:
[Link]( "dept" )

The method returns the following array of distinct dept values:


[ "A", "B" ]

Return Distinct Values for an Embedded Field The following example returns the distinct values for the field
sku, embedded in the item field, from all documents in the inventory collection:
[Link]( "[Link]" )

The method returns the following array of distinct sku values:


[ "111", "222", "333" ]

See also:
document-dot-notation for information on accessing fields within embedded documents

Return Distinct Values for an Array Field The following example returns the distinct values for the field sizes
from all documents in the inventory collection:

2.1. mongo Shell Methods 29


MongoDB Reference Manual, Release 3.0.7

[Link]( "sizes" )

The method returns the following array of distinct sizes values:


[ "M", "S", "L" ]

For information on distinct() (page 28) and array fields, see the Behavior (page 29) section.

Specify Query with distinct The following example returns the distinct values for the field sku, embedded in
the item field, from the documents whose dept is equal to "A":
[Link]( "[Link]", { dept: "A" } )

The method returns the following array of distinct sku values:


[ "111", "333" ]

[Link]()

Definition
[Link]()
Removes a collection from the database. The method also removes any indexes associated with the dropped
collection. The method provides a wrapper around the drop (page 342) command.
[Link]() (page 30) has the form:
[Link]()

[Link]() (page 30) takes no arguments and will produce an error if called with any argu-
ments.
Returns
true when successfully drops a collection.
false when collection to drop does not exist.

Behavior This method obtains a write lock on the affected database and will block other operations until it has
completed.

Example The following operation drops the students collection in the current database.
[Link]()

[Link]()

Definition
[Link](index)
Drops or removes the specified index from a collection. The [Link]() (page 30)
method provides a wrapper around the dropIndexes (page 351) command.

Note: You cannot drop the default index on the _id field.

The [Link]() (page 30) method takes the following parameter:

30 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

param string, document index Specifies the index to drop. You can specify the index either by the
index name or by the index specification document. 2
To drop a text index, specify the index name.
To get the index name or the index specification document for the [Link]()
(page 30) method, use the [Link]() (page 46) method.

Example Consider a pets collection. Calling the getIndexes() (page 46) method on the pets collection
returns the following indexes:
[
{ "v" : 1,
"key" : { "_id" : 1 },
"ns" : "[Link]",
"name" : "_id_"
},
{
"v" : 1,
"key" : { "cat" : -1 },
"ns" : "[Link]",
"name" : "catIdx"
},
{
"v" : 1,
"key" : { "cat" : 1, "dog" : -1 },
"ns" : "[Link]",
"name" : "cat_1_dog_-1"
}
]

The single field index on the field cat has the user-specified name of catIdx 3 and the index specification document
of { "cat" : -1 }.
To drop the index catIdx, you can use either the index name:
[Link]( "catIdx" )

Or you can use the index specification document { "cat" : -1 }:


[Link]( { "cat" : -1 } )

[Link]()

[Link]()
Drops all indexes other than the required index on the _id field. Only call dropIndexes() (page 31) as a
method on a collection object.

[Link]()

Definition
2 When using a mongo (page 632) shell version earlier than 2.2.2, if you specified a name during the index creation, you must use the name to

drop the index.


3 During index creation, if the user does not specify an index name, the system generates the name by concatenating the index key field and

value with an underscore, e.g. cat_1.

2.1. mongo Shell Methods 31


MongoDB Reference Manual, Release 3.0.7

[Link](keys, options)
Deprecated since version 3.0.0: [Link]() (page 31) is now an alias for
[Link]() (page 25).
Creates an index on the specified field if the index does not already exist.

Additional Information
Use [Link]() (page 25) rather than [Link]()
(page 31) to create new indexes.
The [Link] section of this manual for full documentation of
indexes and indexing in MongoDB.
[Link]() (page 46) to view the specifications of existing indexes for a collection.

[Link]()

Description
[Link]()
New in version 3.0.
Returns information on the query plan for the following operations: aggregate() (page 20); count()
(page 23); find() (page 35); group() (page 49); remove() (page 63); and update() (page 70) methods.
To use [Link]() (page 32), append to [Link]() (page 32) the
method(s) available to explain:
[Link]().<method(...)>

For example,
[Link]().remove( { category: "apparel" }, { justOne: true } )

For more examples, see Examples (page 34). For a list of methods available for use with
[Link]() (page 32), see [Link]().help() (page 33).
The [Link]() (page 32) method has the following parameter:
param string verbosity Optional. Specifies the verbosity mode for the explain output. The
mode affects the behavior of explain() and determines the amount of information
to return. The possible modes are: "queryPlanner", "executionStats", and
"allPlansExecution".
Default mode is "queryPlanner".
For backwards compatibility with earlier versions of [Link]() (page 83), Mon-
goDB interprets true as "allPlansExecution" and false as "queryPlanner".
For more information on the modes, see Verbosity Modes (page 32).

Behavior

Verbosity Modes The behavior of [Link]() (page 32) and the amount of information re-
turned depend on the verbosity mode.

32 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

queryPlanner Mode By default, [Link]() (page 32) runs in queryPlanner ver-


bosity mode.
MongoDB runs the query optimizer to choose the winning plan for the operation under evaluation.
[Link]() (page 32) returns the queryPlanner (page 767) information for the evaluated
method.

executionStats Mode MongoDB runs the query optimizer to choose the winning plan, executes the
winning plan to completion, and returns statistics describing the execution of the winning plan.
For write operations, [Link]() (page 32) returns information about the update or delete op-
erations that would be performed, but does not apply the modifications to the database.
[Link]() (page 32) returns the queryPlanner (page 767) and executionStats
(page 768) information for the evaluated method. However, executionStats (page 768) does not provide query
execution information for the rejected plans.

allPlansExecution Mode MongoDB runs the query optimizer to choose the winning plan and executes
the winning plan to completion. In "allPlansExecution" mode, MongoDB returns statistics describing the
execution of the winning plan as well as statistics for the other candidate plans captured during plan selection.
For write operations, [Link]() (page 32) returns information about the update or delete op-
erations that would be performed, but does not apply the modifications to the database.
[Link]() (page 32) returns the queryPlanner (page 767) and executionStats
(page 768) information for the evaluated method. The executionStats (page 768) includes the completed query
execution information for the winning plan.
If the query optimizer considered more than one plan, executionStats (page 768) information also includes the
partial execution information captured during the plan selection phase for both the winning and rejected candidate
plans.

explain() Mechanics The [Link]() (page 32) method wraps the explain (page 364)
command and is the preferred way to run explain (page 364).
[Link]().find() is similar to [Link]().explain() (page 83) with
the following key differences:
The [Link]().find() construct allows for the additional chaining of query modi-
fiers. For list of query modifiers, see [Link]().find().help() (page 33).
The [Link]().find() returns a cursor, which requires a call to .next(), or its
alias .finish(), to return the explain() results. If run interactively in the mongo (page 632) shell,
the mongo (page 632) shell automatically calls .finish() to return the results. For scripts, however, you
must explicitly call .next(), or .finish(), to return the results. For list of cursor-related methods, see
[Link]().find().help() (page 33).
[Link]().aggregate() is equivalent to passing the explain (page 22) option to the
[Link]() (page 20) method.

help() To see the list of operations supported by [Link]() (page 32), run:
[Link]().help()

[Link]().find() returns a cursor, which allows for the chaining of query modifiers. To
see the list of query modifiers supported by [Link]().find() (page 32) as well as cursor-
related methods, run:

2.1. mongo Shell Methods 33


MongoDB Reference Manual, Release 3.0.7

[Link]().find().help()

You can chain multiple modifiers to [Link]().find(). For an example, see Explain find()
with Modifiers (page 34).

Examples

queryPlanner Mode By default, [Link]() (page 32) runs in "queryPlanner" ver-


bosity mode.
The following example runs [Link]() (page 32) in queryPlanner (page 33) verbosity
mode to return the query planning information for the specified count() (page 23) operation:
[Link]().count( { quantity: { $gt: 50 } } )

executionStats Mode The following example runs [Link]() (page 32) in execu-
tionStats (page 33) verbosity mode to return the query planning and execution information for the specified find()
(page 35) operation:
[Link]("executionStats").find(
{ quantity: { $gt: 50 }, category: "apparel" }
)

allPlansExecution Mode The following example runs [Link]() (page 32) in


allPlansExecution (page 33) verbosity mode. The [Link]() (page 32) returns the
queryPlanner (page 767) and executionStats (page 768) for all considered plans for the specified
update() (page 70) operation:

Note: The execution of this explain will not modify data but runs the query predicate of the update operation. For
candidate plans, MongoDB returns the execution information captured during the plan selection phase.

[Link]("allPlansExecution").update(
{ quantity: { $lt: 1000}, category: "apparel" },
{ $set: { reorder: true } }
)

Explain find() with Modifiers [Link]().find() construct allows for the chaining of
query modifiers. For example, the following operation provides information on the find() (page 35) method with
sort() (page 94) and hint() (page 85) query modifiers.
[Link]("executionStats").find(
{ quantity: { $gt: 50 }, category: "apparel" }
).sort( { quantity: -1 } ).hint( { category: 1, quantity: -1 } )

For a list of query modifiers available, run in the mongo (page 632) shell:
[Link]().find().help()

Iterate the explain().find() Return Cursor [Link]().find() returns a cursor


to the explain results. If run interactively in the mongo (page 632) shell, the mongo (page 632) shell automatically
iterates the cursor using the .next() method. For scripts, however, you must explicitly call .next() (or its alias
.finish()) to return the results:

34 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

var explainResult = [Link]().find( { category: "apparel" } ).next();

Output [Link]() (page 32) operations can return information regarding:


queryPlanner (page 766), which details the plan selected by the query optimizer and lists the rejected
plans;
executionStats (page 767), which details the execution of the winning plan and the rejected plans; and
serverInfo (page 769), which provides information on the MongoDB instance.
The verbosity mode (i.e. queryPlanner, executionStats, allPlansExecution) determines whether the
results include executionStats (page 767) and whether executionStats (page 767) includes data captured during plan
selection.
For details on the output, see Explain Results (page 766).
For a mixed version sharded cluster with version 3.0 mongos (page 622) and at least one 2.6 mongod (page 603)
shard, when you run [Link]() (page 32) in a version 3.0 mongo (page 632) shell,
[Link]() (page 32) will retry with the $explain (page 573) operator to return results in
the 2.6 format.

[Link]()

Definition
[Link](query, projection)
4
Selects documents in a collection and returns a cursor to the selected documents.
param document query Optional. Specifies selection criteria using query operators (page 413). To
return all documents in a collection, omit this parameter or pass an empty document ({}).
param document projection Optional. Specifies the fields to return using projection operators
(page 458). To return all fields in the matching document, omit this parameter.

Returns
A cursor to the documents that match the query criteria. When the find() (page 35) method
returns documents, the method is actually returning a cursor to the documents.
If find() (page 35) includes a projection argument, the matching documents contain only
the projection fields and the _id field. You can optionally exclude the _id field.
Executing find() (page 35) directly in the mongo (page 632) shell automatically iterates the
cursor to display up to the first 20 documents. Type it to continue iteration.
To access the returned documents with a driver, use the appropriate cursor handling mechanism
for the driver language.
The projection parameter takes a document of the following form:
{ field1: <boolean>, field2: <boolean> ... }

The <boolean> value can be any of the following:


1 or true to include the field. The find() (page 35) method always includes the _id field even if the field is
not explicitly stated to return in the projection parameter.
0 or false to exclude the field.
4 [Link]() (page 35) is a wrapper for the more formal query structure that uses the $query (page 580) operator. This
operator is necessary to work with documents containing a field name query containing an embedded document.

2.1. mongo Shell Methods 35


MongoDB Reference Manual, Release 3.0.7

A projection cannot contain both include and exclude specifications, except for the exclusion of the _id field. In
projections that explicitly include fields, the _id field is the only field that you can explicitly exclude.

Examples

Find All Documents in a Collection The find() (page 35) method with no parameters returns all documents
from a collection and returns all fields for the documents. For example, the following operation returns all documents
in the bios collection:
[Link]()

Find Documents that Match Query Criteria To find documents that match a set of selection criteria, call find()
with the <criteria> parameter. The following operation returns all the documents from the collection products
where qty is greater than 25:
[Link]( { qty: { $gt: 25 } } )

Query for Equality The following operation returns documents in the bios collection where _id equals 5:
[Link]( { _id: 5 } )

Query Using Operators The following operation returns documents in the bios collection where _id equals
either 5 or ObjectId("507c35dd8fada716c89d0013"):
[Link](
{
_id: { $in: [ 5, ObjectId("507c35dd8fada716c89d0013") ] }
}
)

Query for Ranges Combine comparison operators to specify ranges. The following operation returns documents
with field between value1 and value2:
[Link]( { field: { $gt: value1, $lt: value2 } } );

Query a Field that Contains an Array If a field contains an array and your query has multiple conditional operators,
the field as a whole will match if either a single array element meets the conditions or a combination of array elements
meet the conditions.
Given a collection students that contains the following documents:
{ "_id" : 1, "score" : [ -1, 3 ] }
{ "_id" : 2, "score" : [ 1, 5 ] }
{ "_id" : 3, "score" : [ 5, 5 ] }

The following query:


[Link]( { score: { $gt: 0, $lt: 2 } } )

Matches the following documents:

36 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

{ "_id" : 1, "score" : [ -1, 3 ] }


{ "_id" : 2, "score" : [ 1, 5 ] }

In the document with _id equal to 1, the score: [ -1, 3 ] meets the conditions because the element -1
meets the $lt: 2 condition and the element 3 meets the $gt: 0 condition.
In the document with _id equal to 2, the score: [ 1, 5 ] meets the conditions because the element 1 meets
both the $lt: 2 condition and the $gt: 0 condition.

Query Arrays

Query for an Array Element The following operation returns documents in the bios collection where the
array field contribs contains the element "UNIX":
[Link]( { contribs: "UNIX" } )

Query an Array of Documents The following operation returns documents in the bios collection where
awards array contains an embedded document element that contains the award field equal to "Turing Award"
and the year field greater than 1980:
[Link](
{
awards: {
$elemMatch: {
award: "Turing Award",
year: { $gt: 1980 }
}
}
}
)

Query Embedded Documents

Query Exact Matches on Embedded Documents The following operation returns documents in the
bios collection where the embedded document name is exactly { first: "Yukihiro", last:
"Matsumoto" }, including the order:
[Link](
{
name: {
first: "Yukihiro",
last: "Matsumoto"
}
}
)

The name field must match the embedded document exactly. The query does not match documents with the following
name fields:
{
first: "Yukihiro",
aka: "Matz",
last: "Matsumoto"
}

2.1. mongo Shell Methods 37


MongoDB Reference Manual, Release 3.0.7

{
last: "Matsumoto",
first: "Yukihiro"
}

Query Fields of an Embedded Document The following operation returns documents in the bios collection
where the embedded document name contains a field first with the value "Yukihiro" and a field last with the
value "Matsumoto". The query uses dot notation to access fields in an embedded document:
[Link](
{
"[Link]": "Yukihiro",
"[Link]": "Matsumoto"
}
)

The query matches the document where the name field contains an embedded document with the field first with
the value "Yukihiro" and a field last with the value "Matsumoto". For instance, the query would match
documents with name fields that held either of the following values:
{
first: "Yukihiro",
aka: "Matz",
last: "Matsumoto"
}

{
last: "Matsumoto",
first: "Yukihiro"
}

Projections The projection parameter specifies which fields to return. The parameter contains either include or
exclude specifications, not both, unless the exclude is for the _id field.

Specify the Fields to Return The following operation returns all the documents from the products collection
where qty is greater than 25 and returns only the _id, item and qty fields:
[Link]( { qty: { $gt: 25 } }, { item: 1, qty: 1 } )

The operation returns the following:


{ "_id" : 11, "item" : "pencil", "qty" : 50 }
{ "_id" : ObjectId("50634d86be4617f17bb159cd"), "item" : "bottle", "qty" : 30 }
{ "_id" : ObjectId("50634dbcbe4617f17bb159d0"), "item" : "paper", "qty" : 100 }

The following operation finds all documents in the bios collection and returns only the name field, contribs
field and _id field:
[Link]( { }, { name: 1, contribs: 1 } )

Explicitly Excluded Fields The following operation queries the bios collection and returns all fields except
the first field in the name embedded document and the birth field:

38 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link](
{ contribs: 'OOP' },
{ '[Link]': 0, birth: 0 }
)

Explicitly Exclude the _id Field The following operation excludes the _id and qty fields from the result set:
[Link]( { qty: { $gt: 25 } }, { _id: 0, qty: 0 } )

The documents in the result set contain all fields except the _id and qty fields:
{ "item" : "pencil", "type" : "no.2" }
{ "item" : "bottle", "type" : "blue" }
{ "item" : "paper" }

The following operation finds documents in the bios collection and returns only the name field and the
contribs field:
[Link](
{ },
{ name: 1, contribs: 1, _id: 0 }
)

On Arrays and Embedded Documents The following operation queries the bios collection and returns the
last field in the name embedded document and the first two elements in the contribs array:
[Link](
{ },
{
_id: 0,
'[Link]': 1,
contribs: { $slice: 2 }
}
)

Iterate the Returned Cursor The find() (page 35) method returns a cursor to the results. In the mongo
(page 632) shell, if the returned cursor is not assigned to a variable using the var keyword, the cursor is auto-
matically iterated up to 20 times to access up to the first 20 documents that match the query. You can use the
[Link] to change the number of iterations. See Flags (page 80) and cursor-behaviors. To
iterate manually, assign the returned cursor to a variable using the var keyword.

With Variable Name The following example uses the variable myCursor to iterate over the cursor and print the
matching documents:
var myCursor = [Link]( );

myCursor

With next() Method The following example uses the cursor method next() (page 91) to access the documents:
var myCursor = [Link]( );

var myDocument = [Link]() ? [Link]() : null;

2.1. mongo Shell Methods 39


MongoDB Reference Manual, Release 3.0.7

if (myDocument) {
var myName = [Link];
print (tojson(myName));
}

To print, you can also use the printjson() method instead of print(tojson()):
if (myDocument) {
var myName = [Link];
printjson(myName);
}

With forEach() Method The following example uses the cursor method forEach() (page 84) to iterate the
cursor and access the documents:
var myCursor = [Link]( );

[Link](printjson);

Modify the Cursor Behavior The mongo (page 632) shell and the drivers provide several cursor methods that
call on the cursor returned by the find() (page 35) method to modify its behavior.

Order Documents in the Result Set The sort() (page 94) method orders the documents in the result set. The
following operation returns documents in the bios collection sorted in ascending order by the name field:
[Link]().sort( { name: 1 } )

sort() (page 94) corresponds to the ORDER BY statement in SQL.

Limit the Number of Documents to Return The limit() (page 86) method limits the number of documents in
the result set. The following operation returns at most 5 documents in the bios collection:
[Link]().limit( 5 )

limit() (page 86) corresponds to the LIMIT statement in SQL.

Set the Starting Point of the Result Set The skip() (page 93) method controls the starting point of the results set.
The following operation skips the first 5 documents in the bios collection and returns all remaining documents:
[Link]().skip( 5 )

Combine Cursor Methods The following statements chain cursor methods limit() (page 86) and sort()
(page 94):
[Link]().sort( { name: 1 } ).limit( 5 )
[Link]().limit( 5 ).sort( { name: 1 } )

The two statements are equivalent; i.e. the order in which you chain the limit() (page 86) and the sort()
(page 94) methods is not significant. Both statements return the first five documents, as determined by the ascending
sort order on name.

40 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link]()

Definition
[Link](document)
Modifies and returns a single document. By default, the returned document does not include the modifications
made on the update. To return the document with the modifications made on the update, use the new option. The
findAndModify() (page 41) method is a shell helper around the findAndModify (page 254) command.
The findAndModify() (page 41) method has the following form:
[Link]({
query: <document>,
sort: <document>,
remove: <boolean>,
update: <document>,
new: <boolean>,
fields: <document>,
upsert: <boolean>
});

The [Link]() (page 41) method takes a document parameter with the follow-
ing embedded document fields:
param document query Optional. The selection criteria for the modification. The query field em-
ploys the same query selectors (page 413) as used in the [Link]() (page 35)
method. Although the query may match multiple documents, findAndModify() (page 41)
will only select one document to modify.
param document sort Optional. Determines which document the operation modifies if the query
selects multiple documents. findAndModify() (page 41) modifies the first document in the
sort order specified by this argument.
param boolean remove Must specify either the remove or the update field. Removes the doc-
ument specified in the query field. Set this to true to remove the selected document . The
default is false.
param document update Must specify either the remove or the update field. Performs an up-
date of the selected document. The update field employs the same update operators (page 464)
or field: value specifications to modify the selected document.
param boolean new Optional. When true, returns the modified document rather than the original.
The findAndModify() (page 41) method ignores the new option for remove operations.
The default is false.
param document fields Optional. A subset of fields to return. The fields document specifies an
inclusion of a field with 1, as in: fields: { <field1>: 1, <field2>: 1, ...
}. See projection.
param boolean upsert Optional. Used in conjunction with the update field.
When true, findAndModify() (page 41) creates a new document if no document matches
the query, or if documents match the query, findAndModify() (page 41) performs an
update. To avoid multiple upserts, ensure that the query fields are uniquely indexed.
The default is false.

Return Data For remove operations, if the query matches a document, findAndModify() (page 41) returns
the removed document. If the query does not match a document to remove, findAndModify() (page 41) returns
null.

2.1. mongo Shell Methods 41


MongoDB Reference Manual, Release 3.0.7

For update operations, findAndModify() (page 41) returns one of the following:
If the new parameter is not set or is false:
the pre-modification document if the query matches a document;
otherwise, null.
If new is true:
the modified document if the query returns a match;
the inserted document if upsert: true and no document matches the query;
otherwise, null.
Changed in version 3.0: In previous versions, if for the update, sort is specified, and upsert: true, and the
new option is not set or new: false, [Link]() (page 41) returns an empty
document {} instead of null.

Behavior

Upsert and Unique Index When findAndModify() (page 41) includes the upsert: true option and the
query field(s) is not uniquely indexed, the method could insert a document multiple times in certain circumstances.
In the following example, no document with the name Andy exists, and multiple clients issue the following command:
[Link]({
query: { name: "Andy" },
sort: { rating: 1 },
update: { $inc: { score: 1 } },
upsert: true
})

Then, if these clients findAndModify() (page 41) methods finish the query phase before any command starts
the modify phase, and there is no unique index on the name field, the commands may all perform an upsert, creating
multiple duplicate documents.
To prevent the creation of multiple duplicate documents, create a unique index on the name field. With the unique
index in place, the multiple methods will exhibit one of the following behaviors:
Exactly one findAndModify() (page 41) successfully inserts a new document.
Zero or more findAndModify() (page 41) methods update the newly inserted document.
Zero or more findAndModify() (page 41) methods fail when they attempt to insert a duplicate. If the
method fails due to a unique index constraint violation, you can retry the method. Absent a delete of the
document, the retry should not fail.

Sharded Collections When using findAndModify (page 254) in a sharded environment, the query must con-
tain the shard key for all operations against the shard cluster for the sharded collections.
findAndModify (page 254) operations issued against mongos (page 622) instances for non-sharded collections
function normally.

Comparisons with the update Method When updating a document, findAndModify() (page 41) and the
update() (page 70) method operate differently:
By default, both operations modify a single document. However, the update() (page 70) method with its
multi option can modify more than one document.

42 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

If multiple documents match the update criteria, for findAndModify() (page 41), you can specify a sort
to provide some measure of control on which document to update.
With the default behavior of the update() (page 70) method, you cannot specify which single document to
update when multiple documents match.
By default, findAndModify() (page 41) method returns the pre-modified version of the document. To obtain
the updated document, use the new option.
The update() (page 70) method returns a WriteResult (page 207) object that contains the status of the
operation. To return the updated document, use the find() (page 35) method. However, other updates may
have modified the document between your update and the document retrieval. Also, if the update modified only
a single document but multiple documents matched, you will need to use additional logic to identify the updated
document.
You cannot specify a write concern to findAndModify() (page 41) to override the default write con-
cern whereas, starting in MongoDB 2.6, you can specify a write concern to the update() (page 70) method.
When modifying a single document, both findAndModify() (page 41) and
the update() (page 70) method atomically update the document. See
[Link] for more details
about interactions and order of operations of these methods.

Examples

Update and Return The following method updates and returns an existing document in the people collection where
the document matches the query criteria:
[Link]({
query: { name: "Tom", state: "active", rating: { $gt: 10 } },
sort: { rating: 1 },
update: { $inc: { score: 1 } }
})

This method performs the following actions:


1. The query finds a document in the people collection where the name field has the value Tom, the state
field has the value active and the rating field has a value greater than 10.
2. The sort orders the results of the query in ascending order. If multiple documents meet the query condition,
the method will select for modification the first document as ordered by this sort.
3. The update increments the value of the score field by 1.
4. The method returns the original (i.e. pre-modification) document selected for this update:
{
"_id" : ObjectId("50f1e2c99beb36a0f45c6453"),
"name" : "Tom",
"state" : "active",
"rating" : 100,
"score" : 5
}

To return the modified document, add the new:true option to the method.
If no document matched the query condition, the method returns null.

2.1. mongo Shell Methods 43


MongoDB Reference Manual, Release 3.0.7

Upsert The following method includes the upsert: true option for the update operation to either update a
matching document or, if no matching document exists, create a new document:
[Link]({
query: { name: "Gus", state: "active", rating: 100 },
sort: { rating: 1 },
update: { $inc: { score: 1 } },
upsert: true
})

If the method finds a matching document, the method performs an update.


If the method does not find a matching document, the method creates a new document. Because the method included
the sort option, it returns an empty document { } as the original (pre-modification) document:
{ }

If the method did not include a sort option, the method returns null.
null

Return New Document The following method includes both the upsert: true option and the new:true op-
tion. The method either updates a matching document and returns the updated document or, if no matching document
exists, inserts a document and returns the newly inserted document in the value field.
In the following example, no document in the people collection matches the query condition:
[Link]({
query: { name: "Pascal", state: "active", rating: 25 },
sort: { rating: 1 },
update: { $inc: { score: 1 } },
upsert: true,
new: true
})

The method returns the newly inserted document:


{
"_id" : ObjectId("50f49ad6444c11ac2448a5d6"),
"name" : "Pascal",
"rating" : 25,
"score" : 1,
"state" : "active"
}

Sort and Remove By including a sort specification on the rating field, the following example removes from
the people collection a single document with the state value of active and the lowest rating among the
matching documents:
[Link](
{
query: { state: "active" },
sort: { rating: 1 },
remove: true
}
)

The method returns the deleted document:

44 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

{
"_id" : ObjectId("52fba867ab5fdca1299674ad"),
"name" : "XYZ123",
"score" : 1,
"state" : "active",
"rating" : 3
}

[Link]()

Definition
[Link](query, projection)
Returns one document that satisfies the specified query criteria. If multiple documents satisfy the query, this
method returns the first document according to the natural order which reflects the order of documents on the
disk. In capped collections, natural order is the same as insertion order. If no document satisfies the query, the
method returns null.
param document query Optional. Specifies query selection criteria using query operators
(page 413).
param document projection Optional. Specifies the fields to return using projection operators
(page 458). Omit this parameter to return all fields in the matching document.
The projection parameter takes a document of the following form:
{ field1: <boolean>, field2: <boolean> ... }

The <boolean> can be one of the following include or exclude values:


1 or true to include. The findOne() (page 45) method always includes the _id field even if the field
is not explicitly specified in the projection parameter.
0 or false to exclude.
The projection argument cannot mix include and exclude specifications, with the exception of excluding the
_id field.
Returns
One document that satisfies the criteria specified as the first argument to this method. If you
specify a projection parameter, findOne() (page 45) returns a document that only con-
tains the projection fields. The _id field is always included unless you explicitly exclude
it.
Although similar to the find() (page 35) method, the findOne() (page 45) method returns
a document rather than a cursor.

Examples

With Empty Query Specification The following operation returns a single document from the bios
collection:
[Link]()

2.1. mongo Shell Methods 45


MongoDB Reference Manual, Release 3.0.7

With a Query Specification The following operation returns the first matching document from the bios
collection where either the field first in the embedded document name starts with the letter G or where
the field birth is less than new Date(01/01/1945):
[Link](
{
$or: [
{ '[Link]' : /^G/ },
{ birth: { $lt: new Date('01/01/1945') } }
]
}
)

With a Projection The projection parameter specifies which fields to return. The parameter contains either
include or exclude specifications, not both, unless the exclude is for the _id field.

Specify the Fields to Return The following operation finds a document in the bios collection and returns
only the name, contribs and _id fields:
[Link](
{ },
{ name: 1, contribs: 1 }
)

Return All but the Excluded Fields The following operation returns a document in the bios collection
where the contribs field contains the element OOP and returns all fields except the _id field, the first field in
the name embedded document, and the birth field:
[Link](
{ contribs: 'OOP' },
{ _id: 0, '[Link]': 0, birth: 0 }
)

The findOne Result Document You cannot apply cursor methods to the result of findOne() (page 45) because
a single document is returned. You have access to the document directly:
var myDocument = [Link]();

if (myDocument) {
var myName = [Link];

print (tojson(myName));
}

[Link]()

Definition
[Link]()
Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
You must call [Link]() (page 46) on a collection. For example:
[Link]()

Change collection to the name of the collection for which to return index information.

46 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Considerations Changed in version 3.0.0.


For MongoDB 3.0 deployments using the WiredTiger storage engine, if you run
[Link]() (page 46) from a version of the mongo (page 632) shell before 3.0 or a
version of the driver prior to 3.0 compatible version (page 829), [Link]() (page 46)
will return no data, even if there are existing indexes. For more information, see WiredTiger and Driver Version
Compatibility (page 825).

Output [Link]() (page 46) returns an array of documents that hold index information
for the collection. Index information includes the keys and options used to create the index. For information on the
keys and index options, see [Link]() (page 25).

[Link]()

Definition
[Link]()
Returns
Prints the data distribution statistics for a sharded collection. You must call the
getShardDistribution() (page 47) method on a sharded collection, as in the follow-
ing example:

[Link]()

In the following example, the collection has two shards. The output displays both the individual shard distribu-
tion information as well the total shard distribution:
Shard <shard-a> at <host-a>
data : <size-a> docs : <count-a> chunks : <number of chunks-a>
estimated data per chunk : <size-a>/<number of chunks-a>
estimated docs per chunk : <count-a>/<number of chunks-a>

Shard <shard-b> at <host-b>


data : <size-b> docs : <count-b> chunks : <number of chunks-b>
estimated data per chunk : <size-b>/<number of chunks-b>
estimated docs per chunk : <count-b>/<number of chunks-b>

Totals
data : <[Link]> docs : <[Link]> chunks : <calc total chunks>
Shard <shard-a> contains <estDataPercent-a>% data, <estDocPercent-a>% docs in cluster, avg obj
Shard <shard-b> contains <estDataPercent-b>% data, <estDocPercent-b>% docs in cluster, avg obj
See also:
[Link]

Output The output information displays:


<shard-x> is a string that holds the shard name.
<host-x> is a string that holds the host name(s).
<size-x> is a number that includes the size of the data, including the unit of measure (e.g. b, Mb).
<count-x> is a number that reports the number of documents in the shard.
<number of chunks-x> is a number that reports the number of chunks in the shard.

2.1. mongo Shell Methods 47


MongoDB Reference Manual, Release 3.0.7

<size-x>/<number of chunks-x> is a calculated value that reflects the estimated data size per chunk
for the shard, including the unit of measure (e.g. b, Mb).
<count-x>/<number of chunks-x> is a calculated value that reflects the estimated number of docu-
ments per chunk for the shard.
<[Link]> is a value that reports the total size of the data in the sharded collection, including the unit of
measure.
<[Link]> is a value that reports the total number of documents in the sharded collection.
<calc total chunks> is a calculated number that reports the number of chunks from all shards, for ex-
ample:
<calc total chunks> = <number of chunks-a> + <number of chunks-b>

<estDataPercent-x> is a calculated value that reflects, for each shard, the data size as the percentage of
the collections total data size, for example:
<estDataPercent-x> = <size-x>/<[Link]>

<estDocPercent-x> is a calculated value that reflects, for each shard, the number of documents as the
percentage of the total number of documents for the collection, for example:
<estDocPercent-x> = <count-x>/<[Link]>

[Link][ <shard-x> ].avgObjSize is a number that reflects the average object size, including
the unit of measure, for the shard.

Example Output For example, the following is a sample output for the distribution of a sharded collection:
Shard shard-a at shard-a/[Link],[Link],[Link]
data : 38.14Mb docs : 1000003 chunks : 2
estimated data per chunk : 19.07Mb
estimated docs per chunk : 500001

Shard shard-b at shard-b/[Link],[Link],[Link]


data : 38.14Mb docs : 999999 chunks : 3
estimated data per chunk : 12.71Mb
estimated docs per chunk : 333333

Totals
data : 76.29Mb docs : 2000002 chunks : 5
Shard shard-a contains 50% data, 50% docs in cluster, avg obj size on shard : 40b
Shard shard-b contains 49.99% data, 49.99% docs in cluster, avg obj size on shard : 40b

[Link]()

[Link]()
This method returns information regarding the state of data in a sharded cluster that is useful when diagnosing
underlying issues with a sharded cluster.
For internal and diagnostic use only.

[Link]()

Recommended Alternatives

48 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Because [Link]() (page 49) uses JavaScript, it is subject to a number of performance limi-
tations. For most cases the $group (page 508) operator in the aggregation pipeline provides a suitable
alternative with fewer restrictions.

Definition
[Link]({ key, reduce, initial [, keyf] [, cond] [, finalize] })
Groups documents in a collection by the specified keys and performs simple aggregation functions such as
computing counts and sums. The method is analogous to a SELECT <...> GROUP BY statement in SQL.
The group() (page 49) method returns an array.
The [Link]() (page 49) accepts a single document that contains the following:
field document key The field or fields to group. Returns a key object for use as the grouping key.
field function reduce An aggregation function that operates on the documents during the grouping
operation. These functions may return a sum or a count. The function takes two arguments: the
current document and an aggregation result document for that group.
field document initial Initializes the aggregation result document.
field function keyf Optional. Alternative to the key field. Specifies a function that creates a key
object for use as the grouping key. Use keyf instead of key to group by calculated fields
rather than existing document fields.
field document cond The selection criteria to determine which documents in the collection to pro-
cess. If you omit the cond field, [Link]() (page 49) processes all the
documents in the collection for the group operation.
field function finalize Optional. A function that runs each item in the result set before
[Link]() (page 49) returns the final value. This function can either mod-
ify the result document or replace the result document as a whole.
The [Link]() (page 49) method is a shell wrapper for the group (page 226) command.
However, the [Link]() (page 49) method takes the keyf field and the reduce field
whereas the group (page 226) command takes the $keyf field and the $reduce field.

Behavior

Limits and Restrictions The [Link]() (page 49) method does not work with sharded clusters.
Use the aggregation framework or map-reduce in sharded environments.
The result set must fit within the maximum BSON document size (page 759).
In version 2.2, the returned array can contain at most 20,000 elements; i.e. at most 20,000 unique groupings. For group
by operations that results in more than 20,000 unique groupings, use mapReduce (page 230). Previous versions had
a limit of 10,000 elements.
Prior to 2.4, the [Link]() (page 49) method took the mongod (page 603) instances JavaScript
lock, which blocked all other JavaScript execution.

mongo Shell JavaScript Functions/Properties Changed in version 2.4: In MongoDB 2.4, map-reduce
operations (page 230), the group (page 226) command, and $where (page 435) operator expressions cannot
access certain global functions or properties, such as db, that are available in the mongo (page 632) shell.
When upgrading to MongoDB 2.4, you will need to refactor your code if your map-reduce operations
(page 230), group (page 226) commands, or $where (page 435) operator expressions include any global shell
functions or properties that are no longer available, such as db.

2.1. mongo Shell Methods 49


MongoDB Reference Manual, Release 3.0.7

The following JavaScript functions and properties are available to map-reduce operations (page 230), the
group (page 226) command, and $where (page 435) operator expressions in MongoDB 2.4:
Available Properties Available Functions

args assert() Map()


MaxKey BinData() MD5()
MinKey DBPointer() NumberInt()
DBRef() NumberLong()
doassert() ObjectId()
emit() print()
gc() printjson()
HexData() printjsononeline()
hex_md5() sleep()
isNumber() Timestamp()
isObject() tojson()
ISODate() tojsononeline()
isString() tojsonObject()
UUID()
version()

Examples The following examples assume an orders collection with documents of the following prototype:
{
_id: ObjectId("5085a95c8fada716c89d0021"),
ord_dt: ISODate("2012-07-01T[Link]Z"),
ship_dt: ISODate("2012-07-02T[Link]Z"),
item: { sku: "abc123",
price: 1.99,
uom: "pcs",
qty: 25 }
}

Group by Two Fields The following example groups by the ord_dt and [Link] fields those documents that
have ord_dt greater than 01/01/2011:
[Link](
{
key: { ord_dt: 1, '[Link]': 1 },
cond: { ord_dt: { $gt: new Date( '01/01/2012' ) } },
reduce: function ( curr, result ) { },
initial: { }
}
)

The result is an array of documents that contain the group by fields:


[
{ "ord_dt" : ISODate("2012-07-01T[Link]Z"), "[Link]" : "abc123"},
{ "ord_dt" : ISODate("2012-07-01T[Link]Z"), "[Link]" : "abc456"},
{ "ord_dt" : ISODate("2012-07-01T[Link]Z"), "[Link]" : "bcd123"},
{ "ord_dt" : ISODate("2012-07-01T[Link]Z"), "[Link]" : "efg456"},

50 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

{ "ord_dt" : ISODate("2012-06-01T[Link]Z"), "[Link]" : "abc123"},


{ "ord_dt" : ISODate("2012-06-01T[Link]Z"), "[Link]" : "efg456"},
{ "ord_dt" : ISODate("2012-06-01T[Link]Z"), "[Link]" : "ijk123"},
{ "ord_dt" : ISODate("2012-05-01T[Link]Z"), "[Link]" : "abc123"},
{ "ord_dt" : ISODate("2012-05-01T[Link]Z"), "[Link]" : "abc456"},
{ "ord_dt" : ISODate("2012-06-08T[Link]Z"), "[Link]" : "abc123"},
{ "ord_dt" : ISODate("2012-06-08T[Link]Z"), "[Link]" : "abc456"}
]

The method call is analogous to the SQL statement:


SELECT ord_dt, item_sku
FROM orders
WHERE ord_dt > '01/01/2012'
GROUP BY ord_dt, item_sku

Calculate the Sum The following example groups by the ord_dt and [Link] fields, those documents that
have ord_dt greater than 01/01/2011 and calculates the sum of the qty field for each grouping:
[Link](
{
key: { ord_dt: 1, '[Link]': 1 },
cond: { ord_dt: { $gt: new Date( '01/01/2012' ) } },
reduce: function( curr, result ) {
[Link] += [Link];
},
initial: { total : 0 }
}
)

The result is an array of documents that contain the group by fields and the calculated aggregation field:
[ { "ord_dt" : ISODate("2012-07-01T[Link]Z"), "[Link]" : "abc123", "total" : 25 },
{ "ord_dt" : ISODate("2012-07-01T[Link]Z"), "[Link]" : "abc456", "total" : 25 },
{ "ord_dt" : ISODate("2012-07-01T[Link]Z"), "[Link]" : "bcd123", "total" : 10 },
{ "ord_dt" : ISODate("2012-07-01T[Link]Z"), "[Link]" : "efg456", "total" : 10 },
{ "ord_dt" : ISODate("2012-06-01T[Link]Z"), "[Link]" : "abc123", "total" : 25 },
{ "ord_dt" : ISODate("2012-06-01T[Link]Z"), "[Link]" : "efg456", "total" : 15 },
{ "ord_dt" : ISODate("2012-06-01T[Link]Z"), "[Link]" : "ijk123", "total" : 20 },
{ "ord_dt" : ISODate("2012-05-01T[Link]Z"), "[Link]" : "abc123", "total" : 45 },
{ "ord_dt" : ISODate("2012-05-01T[Link]Z"), "[Link]" : "abc456", "total" : 25 },
{ "ord_dt" : ISODate("2012-06-08T[Link]Z"), "[Link]" : "abc123", "total" : 25 },
{ "ord_dt" : ISODate("2012-06-08T[Link]Z"), "[Link]" : "abc456", "total" : 25 } ]

The method call is analogous to the SQL statement:


SELECT ord_dt, item_sku, SUM(item_qty) as total
FROM orders
WHERE ord_dt > '01/01/2012'
GROUP BY ord_dt, item_sku

Calculate Sum, Count, and Average The following example groups by the calculated day_of_week field, those
documents that have ord_dt greater than 01/01/2011 and calculates the sum, count, and average of the qty field
for each grouping:
[Link](
{

2.1. mongo Shell Methods 51


MongoDB Reference Manual, Release 3.0.7

keyf: function(doc) {
return { day_of_week: doc.ord_dt.getDay() };
},
cond: { ord_dt: { $gt: new Date( '01/01/2012' ) } },
reduce: function( curr, result ) {
[Link] += [Link];
[Link]++;
},
initial: { total : 0, count: 0 },
finalize: function(result) {
var weekdays = [
"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday",
"Friday", "Saturday"
];
result.day_of_week = weekdays[result.day_of_week];
[Link] = [Link]([Link] / [Link]);
}
}
)

The result is an array of documents that contain the group by fields and the calculated aggregation field:
[
{ "day_of_week" : "Sunday", "total" : 70, "count" : 4, "avg" : 18 },
{ "day_of_week" : "Friday", "total" : 110, "count" : 6, "avg" : 18 },
{ "day_of_week" : "Tuesday", "total" : 70, "count" : 3, "avg" : 23 }
]

See also:
[Link]

[Link]()

Definition
[Link]()
Inserts a document or documents into a collection.
The insert() (page 52) method has the following syntax:
Changed in version 2.6.
[Link](
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)

param document, array document A document or array of documents to insert into the collection.
param document writeConcern Optional. A document expressing the write concern. Omit
to use the default write concern. See Safe Writes (page 53).
New in version 2.6.

52 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

param boolean ordered Optional. If true, perform an ordered insert of the documents in the
array, and if an error occurs with one of documents, MongoDB will return without processing
the remaining documents in the array.
If false, perform an unordered insert, and if an error occurs with one of documents, continue
processing the remaining documents in the array.
Defaults to true.
New in version 2.6.

Changed in version 2.6: The insert() (page 52) returns an object that contains the status of the operation.
Returns
A WriteResult (page 55) object for single inserts.
A BulkWriteResult (page 55) object for bulk inserts.

Behaviors

Safe Writes Changed in version 2.6.


The insert() (page 52) method uses the insert (page 244) command, which uses the default write concern. To
specify a different write concern, include the write concern in the options parameter.

Create Collection If the collection does not exist, then the insert() (page 52) method will create the collection.

_id Field If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique
[Link] for the document before inserting. Most
drivers create an ObjectId and insert the _id field, but the mongod (page 603) will create and populate the _id if the
driver or application does not.
If the document contains an _id field, the _id value must be unique within the collection to avoid duplicate key error.

Examples The following examples insert documents into the products collection. If the collection does not exist,
the insert() (page 52) method creates the collection.

Insert a Document without Specifying an _id Field In the following example, the document passed to the
insert() (page 52) method does not contain the _id field:
[Link]( { item: "card", qty: 15 } )

During the insert, mongod (page 603) will create the _id field and assign it a unique
[Link] value, as verified by the inserted
document:
{ "_id" : ObjectId("5063114bd386d8fadbd6b004"), "item" : "card", "qty" : 15 }

The ObjectId values are specific to the machine and time when the operation is run. As such, your values may
differ from those in the example.

2.1. mongo Shell Methods 53


MongoDB Reference Manual, Release 3.0.7

Insert a Document Specifying an _id Field In the following example, the document passed to the insert()
(page 52) method includes the _id field. The value of _id must be unique within the collection to avoid duplicate
key error.
[Link]( { _id: 10, item: "box", qty: 20 } )

The operation inserts the following document in the products collection:


{ "_id" : 10, "item" : "box", "qty" : 20 }

Insert Multiple Documents The following example performs a bulk insert of three documents by passing an array
of documents to the insert() (page 52) method. By default, MongoDB performs an ordered insert. With ordered
inserts, if an error occurs during an insert of one of the documents, MongoDB returns on error without processing the
remaining documents in the array.
The documents in the array do not need to have the same fields. For instance, the first document in the array has an
_id field and a type field. Because the second and third documents do not contain an _id field, mongod (page 603)
will create the _id field for the second and third documents during the insert:
[Link](
[
{ _id: 11, item: "pencil", qty: 50, type: "no.2" },
{ item: "pen", qty: 20 },
{ item: "eraser", qty: 25 }
]
)

The operation inserted the following three documents:


{ "_id" : 11, "item" : "pencil", "qty" : 50, "type" : "no.2" }
{ "_id" : ObjectId("51e0373c6f35bd826f47e9a0"), "item" : "pen", "qty" : 20 }
{ "_id" : ObjectId("51e0373c6f35bd826f47e9a1"), "item" : "eraser", "qty" : 25 }

Perform an Unordered Insert The following example performs an unordered insert of three documents. With
unordered inserts, if an error occurs during an insert of one of the documents, MongoDB continues to insert the
remaining documents in the array.
[Link](
[
{ _id: 20, item: "lamp", qty: 50, type: "desk" },
{ _id: 21, item: "lamp", qty: 20, type: "floor" },
{ _id: 22, item: "bulk", qty: 100 }
],
{ ordered: false }
)

Override Default Write Concern The following operation to a replica set specifies a write concern of "w:
majority" with a wtimeout of 5000 milliseconds such that the method returns after the write propagates to a
majority of the voting replica set members or the method times out after 5 seconds.
Changed in version 3.0: In previous versions, majority referred to the majority of all members of the replica set.
[Link](
{ item: "envelopes", qty : 100, type: "Clasp" },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)

54 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

WriteResult Changed in version 2.6.


When passed a single document, insert() (page 52) returns a WriteResult object.

Successful Results The insert() (page 52) returns a WriteResult (page 207) object that contains the status of
the operation. Upon success, the WriteResult (page 207) object contains information on the number of documents
inserted:
WriteResult({ "nInserted" : 1 })

Write Concern Errors If the insert() (page 52) method encounters write concern errors, the results include the
[Link] (page 207) field:
WriteResult({
"nInserted" : 1,
"writeConcernError" : {
"code" : 64,
"errmsg" : "waiting for replication timed out at shard-a"
}
})

Errors Unrelated to Write Concern If the insert() (page 52) method encounters a non-write concern error, the
results include the [Link] (page 207) field:
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: [Link].$_i
}
})

BulkWriteResult Changed in version 2.6.


When passed an array of documents, insert() (page 52) returns a BulkWriteResult() (page 208) object. See
BulkWriteResult() (page 208) for details.

[Link]()

[Link]()
Returns Returns true if the collection is a capped collection, otherwise returns false.
See also:
[Link]

[Link]()

[Link](map, reduce, {<out>, <query>, <sort>, <limit>, <finalize>, <scope>,


<jsMode>, <verbose>})
The [Link]() (page 55) method provides a wrapper around the mapReduce
(page 230) command.

2.1. mongo Shell Methods 55


MongoDB Reference Manual, Release 3.0.7

[Link](
<map>,
<reduce>,
{
out: <collection>,
query: <document>,
sort: <document>,
limit: <number>,
finalize: <function>,
scope: <document>,
jsMode: <boolean>,
verbose: <boolean>
}
)

[Link]() (page 55) takes the following parameters:


param function map A JavaScript function that associates or maps a value with a key and
emits the key and value pair.
See Requirements for the map Function (page 57) for more information.
param function reduce A JavaScript function that reduces to a single object all the values
associated with a particular key.
See Requirements for the reduce Function (page 58) for more information.
param document options A document that specifies additional parameters to
[Link]() (page 55).
The following table describes additional arguments that [Link]() (page 55) can
accept.
field string or document out Specifies the location of the result of the map-reduce operation. You
can output to a collection, output to a collection with an action, or output inline. You may output
to a collection when performing map reduce operations on the primary members of the set; on
secondary members you may only use the inline output.
See out Options (page 59) for more information.
field document query Specifies the selection criteria using query operators (page 413) for deter-
mining the documents input to the map function.
field document sort Sorts the input documents. This option is useful for optimization. For example,
specify the sort key to be the same as the emit key so that there are fewer reduce operations. The
sort key must be in an existing index for this collection.
field number limit Specifies a maximum number of documents for the input into the map function.
field function finalize Optional. Follows the reduce method and modifies the output.
See Requirements for the finalize Function (page 60) for more information.
field document scope Specifies global variables that are accessible in the map, reduce and
finalize functions.
field boolean jsMode Specifies whether to convert intermediate data into BSON format between the
execution of the map and reduce functions. Defaults to false.
If false:

56 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Internally, MongoDB converts the JavaScript objects emitted by the map function to BSON
objects. These BSON objects are then converted back to JavaScript objects when calling the
reduce function.
The map-reduce operation places the intermediate BSON objects in temporary, on-disk stor-
age. This allows the map-reduce operation to execute over arbitrarily large data sets.
If true:
Internally, the JavaScript objects emitted during map function remain as JavaScript objects.
There is no need to convert the objects for the reduce function, which can result in faster
execution.
You can only use jsMode for result sets with fewer than 500,000 distinct key arguments
to the mappers emit() function.
The jsMode defaults to false.
field boolean verbose Specifies whether to include the timing information in the result informa-
tion. The verbose defaults to true to include the timing information.

Note: Changed in version 2.4.


In MongoDB 2.4, map-reduce operations (page 230), the group (page 226) command, and $where
(page 435) operator expressions cannot access certain global functions or properties, such as db, that are avail-
able in the mongo (page 632) shell.
When upgrading to MongoDB 2.4, you will need to refactor your code if your map-reduce operations
(page 230), group (page 226) commands, or $where (page 435) operator expressions include any global shell
functions or properties that are no longer available, such as db.
The following JavaScript functions and properties are available to map-reduce operations (page 230),
the group (page 226) command, and $where (page 435) operator expressions in MongoDB 2.4:
Available Properties Available Functions

args assert() Map()


MaxKey BinData() MD5()
MinKey DBPointer() NumberInt()
DBRef() NumberLong()
doassert() ObjectId()
emit() print()
gc() printjson()
HexData() printjsononeline()
hex_md5() sleep()
isNumber() Timestamp()
isObject() tojson()
ISODate() tojsononeline()
isString() tojsonObject()
UUID()
version()

Requirements for the map Function The map function is responsible for transforming each input document into
zero or more documents. It can access the variables defined in the scope parameter, and has the following prototype:

2.1. mongo Shell Methods 57


MongoDB Reference Manual, Release 3.0.7

function() {
...
emit(key, value);
}

The map function has the following requirements:


In the map function, reference the current document as this within the function.
The map function should not access the database for any reason.
The map function should be pure, or have no impact outside of the function (i.e. side effects.)
A single emit can only hold half of MongoDBs maximum BSON document size (page 759).
The map function may optionally call emit(key,value) any number of times to create an output document
associating key with value.
The following map function will call emit(key,value) either 0 or 1 times depending on the value of the input
documents status field:
function() {
if ([Link] == 'A')
emit(this.cust_id, 1);
}

The following map function may call emit(key,value) multiple times depending on the number of elements in
the input documents items field:
function() {
[Link](function(item){ emit([Link], 1); });
}

Requirements for the reduce Function The reduce function has the following prototype:
function(key, values) {
...
return result;
}

The reduce function exhibits the following behaviors:


The reduce function should not access the database, even to perform read operations.
The reduce function should not affect the outside system.
MongoDB will not call the reduce function for a key that has only a single value. The values argument is
an array whose elements are the value objects that are mapped to the key.
MongoDB can invoke the reduce function more than once for the same key. In this case, the previous output
from the reduce function for that key will become one of the input values to the next reduce function
invocation for that key.
The reduce function can access the variables defined in the scope parameter.
The inputs to reduce must not be larger than half of MongoDBs maximum BSON document size (page 759).
This requirement may be violated when large documents are returned and then joined together in subsequent
reduce steps.
Because it is possible to invoke the reduce function more than once for the same key, the following properties need
to be true:

58 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

the type of the return object must be identical to the type of the value emitted by the map function.
the reduce function must be associative. The following statement must be true:
reduce(key, [ C, reduce(key, [ A, B ]) ] ) == reduce( key, [ C, A, B ] )

the reduce function must be idempotent. Ensure that the following statement is true:
reduce( key, [ reduce(key, valuesArray) ] ) == reduce( key, valuesArray )

the reduce function should be commutative: that is, the order of the elements in the valuesArray should
not affect the output of the reduce function, so that the following statement is true:
reduce( key, [ A, B ] ) == reduce( key, [ B, A ] )

out Options You can specify the following options for the out parameter:

Output to a Collection This option outputs to a new collection, and is not available on secondary members of replica
sets.
out: <collectionName>

Output to a Collection with an Action This option is only available when passing a collection that already exists
to out. It is not available on secondary members of replica sets.
out: { <action>: <collectionName>
[, db: <dbName>]
[, sharded: <boolean> ]
[, nonAtomic: <boolean> ] }

When you output to a collection with an action, the out has the following parameters:
<action>: Specify one of the following actions:
replace
Replace the contents of the <collectionName> if the collection with the <collectionName> ex-
ists.
merge
Merge the new result with the existing result if the output collection already exists. If an existing document
has the same key as the new result, overwrite that existing document.
reduce
Merge the new result with the existing result if the output collection already exists. If an existing document
has the same key as the new result, apply the reduce function to both the new and the existing documents
and overwrite the existing document with the result.
db:
Optional. The name of the database that you want the map-reduce operation to write its output. By default this
will be the same database as the input collection.
sharded:
Optional. If true and you have enabled sharding on output database, the map-reduce operation will shard the
output collection using the _id field as the shard key.

2.1. mongo Shell Methods 59


MongoDB Reference Manual, Release 3.0.7

nonAtomic:
New in version 2.2.
Optional. Specify output operation as non-atomic. This applies only to the merge and reduce output modes,
which may take minutes to execute.
By default nonAtomic is false, and the map-reduce operation locks the database during post-processing.
If nonAtomic is true, the post-processing step prevents MongoDB from locking the database: during this
time, other clients will be able to read intermediate states of the output collection.

Output Inline Perform the map-reduce operation in memory and return the result. This option is the only available
option for out on secondary members of replica sets.
out: { inline: 1 }

The result must fit within the maximum size of a BSON document (page 759).

Requirements for the finalize Function The finalize function has the following prototype:
function(key, reducedValue) {
...
return modifiedObject;
}

The finalize function receives as its arguments a key value and the reducedValue from the reduce function.
Be aware that:
The finalize function should not access the database for any reason.
The finalize function should be pure, or have no impact outside of the function (i.e. side effects.)
The finalize function can access the variables defined in the scope parameter.

Map-Reduce Examples Consider the following map-reduce operations on a collection orders that contains doc-
uments of the following prototype:
{
_id: ObjectId("50a8240b927d5d8b5891743c"),
cust_id: "abc123",
ord_date: new Date("Oct 04, 2012"),
status: 'A',
price: 25,
items: [ { sku: "mmm", qty: 5, price: 2.5 },
{ sku: "nnn", qty: 5, price: 2.5 } ]
}

Return the Total Price Per Customer Perform the map-reduce operation on the orders collection to group by
the cust_id, and calculate the sum of the price for each cust_id:
1. Define the map function to process each input document:
In the function, this refers to the document that the map-reduce operation is processing.
The function maps the price to the cust_id for each document and emits the cust_id and price
pair.

60 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

var mapFunction1 = function() {


emit(this.cust_id, [Link]);
};

2. Define the corresponding reduce function with two arguments keyCustId and valuesPrices:
The valuesPrices is an array whose elements are the price values emitted by the map function and
grouped by keyCustId.
The function reduces the valuesPrice array to the sum of its elements.
var reduceFunction1 = function(keyCustId, valuesPrices) {
return [Link](valuesPrices);
};

3. Perform the map-reduce on all documents in the orders collection using the mapFunction1 map function
and the reduceFunction1 reduce function.
[Link](
mapFunction1,
reduceFunction1,
{ out: "map_reduce_example" }
)

This operation outputs the results to a collection named map_reduce_example. If the


map_reduce_example collection already exists, the operation will replace the contents with the re-
sults of this map-reduce operation:

Calculate Order and Total Quantity with Average Quantity Per Item In this example, you will perform a
map-reduce operation on the orders collection for all documents that have an ord_date value greater than
01/01/2012. The operation groups by the [Link] field, and calculates the number of orders and the total
quantity ordered for each sku. The operation concludes by calculating the average quantity per order for each sku
value:
1. Define the map function to process each input document:
In the function, this refers to the document that the map-reduce operation is processing.
For each item, the function associates the sku with a new object value that contains the count of 1
and the item qty for the order and emits the sku and value pair.
var mapFunction2 = function() {
for (var idx = 0; idx < [Link]; idx++) {
var key = [Link][idx].sku;
var value = {
count: 1,
qty: [Link][idx].qty
};
emit(key, value);
}
};

2. Define the corresponding reduce function with two arguments keySKU and countObjVals:
countObjVals is an array whose elements are the objects mapped to the grouped keySKU values
passed by map function to the reducer function.
The function reduces the countObjVals array to a single object reducedValue that contains the
count and the qty fields.

2.1. mongo Shell Methods 61


MongoDB Reference Manual, Release 3.0.7

In reducedVal, the count field contains the sum of the count fields from the individual array ele-
ments, and the qty field contains the sum of the qty fields from the individual array elements.
var reduceFunction2 = function(keySKU, countObjVals) {
reducedVal = { count: 0, qty: 0 };

for (var idx = 0; idx < [Link]; idx++) {


[Link] += countObjVals[idx].count;
[Link] += countObjVals[idx].qty;
}

return reducedVal;
};

3. Define a finalize function with two arguments key and reducedVal. The function modifies the
reducedVal object to add a computed field named avg and returns the modified object:
var finalizeFunction2 = function (key, reducedVal) {

[Link] = [Link]/[Link];

return reducedVal;

};

4. Perform the map-reduce operation on the orders collection using the mapFunction2,
reduceFunction2, and finalizeFunction2 functions.
[Link]( mapFunction2,
reduceFunction2,
{
out: { merge: "map_reduce_example" },
query: { ord_date:
{ $gt: new Date('01/01/2012') }
},
finalize: finalizeFunction2
}
)

This operation uses the query field to select only those documents with ord_date greater than new
Date(01/01/2012). Then it output the results to a collection map_reduce_example. If the
map_reduce_example collection already exists, the operation will merge the existing contents with the
results of this map-reduce operation.

Output The output of the [Link]() (page 55) method is identical to that of the
mapReduce (page 230) command. See the Output (page 237) section of the mapReduce (page 230) command
for information on the [Link]() (page 55) output.

Additional Information
[Link]
[Link]
mapReduce (page 230) command
[Link]
Map-Reduce

62 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link]

[Link]()

[Link]()
The [Link]() (page 63) drops all indexes on a collection and recreates them. This
operation may be expensive for collections that have a large amount of data and/or a large number of indexes.
Call this method, which takes no arguments, on a collection object. For example:
[Link]()

Normally, MongoDB compacts indexes during routine updates. For most users, the
[Link]() (page 63) is unnecessary. However, it may be worth running if the
collection size has changed significantly or if the indexes are consuming a disproportionate amount of disk
space.

Behavior
Note: For replica sets, [Link]() (page 63) will not propagate from the primary to secon-
daries. [Link]() (page 63) will only affect a single mongod (page 603) instance.

Important: [Link]() (page 63) will rebuild indexes in the background if the index was
originally specified with this option. However, [Link]() (page 63) will rebuild the _id
index in the foreground, which takes the databases write lock.

Changed in version 2.6: Reindexing operations will error if the index entry for an indexed field exceeds the Maximum
Index Key Length. Reindexing operations occur as part of compact (page 354) and repairDatabase
(page 360) commands as well as the [Link]() (page 63) method.
Because these operations drop all the indexes from a collection and then recreate them sequentially, the error from the
Maximum Index Key Length prevents these operations from rebuilding any remaining indexes for the collection
and, in the case of the repairDatabase (page 360) command, from continuing with the remainder of the process.

See
[Link] for more information on the behavior of
indexing operations in MongoDB.

[Link]()

Definition
[Link]()
Removes documents from a collection.
The [Link]() (page 63) method can have one of two syntaxes. The remove()
(page 63) method can take a query document and an optional justOne boolean:
[Link](
<query>,
<justOne>
)

Or the method can take a query document and an optional remove options document:
New in version 2.6.

2.1. mongo Shell Methods 63


MongoDB Reference Manual, Release 3.0.7

[Link](
<query>,
{
justOne: <boolean>,
writeConcern: <document>
}
)

param document query Specifies deletion criteria using query operators (page 413). To delete all
documents in a collection, pass an empty document ({}).
Changed in version 2.6: In previous versions, the method invoked with no query parameter
deleted all documents in a collection.
param boolean justOne Optional. To limit the deletion to just one document, set to true. Omit to
use the default value of false and delete all documents matching the deletion criteria.
param document writeConcern Optional. A document expressing the write concern. Omit
to use the default write concern. See Safe Writes (page 64).
New in version 2.6.

Changed in version 2.6: The remove() (page 63) returns an object that contains the status of the operation.
Returns A WriteResult (page 65) object that contains the status of the operation.

Behavior

Safe Writes Changed in version 2.6.


The remove() (page 63) method uses the delete (page 251) command, which uses the default write concern. To
specify a different write concern, include the write concern in the options parameter.

Query Considerations By default, remove() (page 63) removes all documents that match the query expression.
Specify the justOne option to limit the operation to removing a single document. To delete a single document sorted
by a specified order, use the findAndModify() (page 44) method.
When removing multiple documents, the remove operation may interleave with other read and/or write operations to
the collection. For unsharded collections, you can override this behavior with the $isolated (page 496) operator,
which isolates the remove operation and disallows yielding during the operation. This ensures that no client can see
the affected documents until they are all processed or an error stops the remove operation.
See Isolate Remove Operations (page 65) for an example.

Capped Collections You cannot use the remove() (page 63) method with a capped collection.

Sharded Collections All remove() (page 63) operations for a sharded collection that specify the justOne option
must include the shard key or the _id field in the query specification. remove() (page 63) operations specifying
justOne in a sharded collection without the shard key or the _id field return an error.

Examples The following are examples of the remove() (page 63) method.

64 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Remove All Documents from a Collection To remove all documents in a collection, call the remove (page 63)
method with an empty query document {}. The following operation deletes all documents from the bios
collection:
[Link]( { } )

This operation is not equivalent to the drop() (page 30) method.


To remove all documents from a collection, it may be more efficient to use the drop() (page 30) method to drop the
entire collection, including the indexes, and then recreate the collection and rebuild the indexes.

Remove All Documents that Match a Condition To remove the documents that match a deletion criteria, call the
remove() (page 63) method with the <query> parameter:
The following operation removes all the documents from the collection products where qty is greater than 20:
[Link]( { qty: { $gt: 20 } } )

Override Default Write Concern The following operation to a replica set removes all the documents from the
collection products where qty is greater than 20 and specifies a write concern of "w: majority" with
a wtimeout of 5000 milliseconds such that the method returns after the write propagates to a majority of the voting
replica set members or the method times out after 5 seconds.
Changed in version 3.0: In previous versions, majority referred to the majority of all members of the replica set.
[Link](
{ qty: { $gt: 20 } },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)

Remove a Single Document that Matches a Condition To remove the first document that match a deletion criteria,
call the remove (page 63) method with the query criteria and the justOne parameter set to true or 1.
The following operation removes the first document from the collection products where qty is greater than 20:
[Link]( { qty: { $gt: 20 } }, true )

Isolate Remove Operations To isolate the query, include $isolated: 1 in the <query> parameter as in the
following examples:
[Link]( { qty: { $gt: 20 }, $isolated: 1 } )

WriteResult Changed in version 2.6.

Successful Results The remove() (page 63) returns a WriteResult (page 207) object that contains the status of
the operation. Upon success, the WriteResult (page 207) object contains information on the number of documents
removed:
WriteResult({ "nRemoved" : 4 })

See also:
[Link] (page 207)

2.1. mongo Shell Methods 65


MongoDB Reference Manual, Release 3.0.7

Write Concern Errors If the remove() (page 63) method encounters write concern errors, the results include the
[Link] (page 207) field:
WriteResult({
"nRemoved" : 21,
"writeConcernError" : {
"code" : 64,
"errInfo" : {
"wtimeout" : true
},
"errmsg" : "waiting for replication timed out"
}
})

See also:
[Link]() (page 208)

Errors Unrelated to Write Concern If the remove() (page 63) method encounters a non-write concern error, the
results include [Link] (page 207) field:
WriteResult({
"nRemoved" : 0,
"writeError" : {
"code" : 2,
"errmsg" : "unknown top level operator: $invalidFieldName"
}
})

See also:
[Link]() (page 208)

[Link]()

Definition
[Link](target, dropTarget)
Renames a collection. Provides a wrapper for the renameCollection (page 334) database command.
param string target The new name of the collection. Enclose the string in quotes.
param boolean dropTarget Optional. If true, mongod (page 603) drops the target of
renameCollection (page 334) prior to renaming the collection. The default value is
false.

Example Call the [Link]() (page 66) method on a collection object. For
example:
[Link]("record")

This operation will rename the rrecord collection to record. If the target name (i.e. record) is the name of an
existing collection, then the operation will fail.

Limitations The method has the following limitations:


[Link]() (page 66) cannot move a collection between databases. Use
renameCollection (page 334) for these rename operations.

66 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link]() (page 66) is not supported on sharded collections.


The [Link]() (page 66) method operates within a collection by changing the
metadata associated with a given collection.
Refer to the documentation renameCollection (page 334) for additional warnings and messages.

Warning: The [Link]() (page 66) method and renameCollection


(page 334) command will invalidate open cursors which interrupts queries that are currently returning data.

[Link]()

Definition
[Link]()
Updates an existing document or inserts a new document, depending on its document parameter.
The save() (page 67) method has the following form:
Changed in version 2.6.
[Link](
<document>,
{
writeConcern: <document>
}
)

param document document A document to save to the collection.


param document writeConcern Optional. A document expressing the write concern. Omit
to use the default write concern. See Safe Writes (page 67).
New in version 2.6.

Changed in version 2.6: The save() (page 67) returns an object that contains the status of the operation.
Returns A WriteResult (page 69) object that contains the status of the operation.

Behavior

Safe Writes Changed in version 2.6.


The save() (page 67) method uses either the insert (page 244) or the update (page 246) command, which use
the default write concern. To specify a different write concern, include the write concern in the options parameter.

Insert If the document does not contain an _id field, then the save() (page 67) method calls the
insert() (page 52) method. During the operation, the mongo (page 632) shell will create an
[Link] and assign it to the _id field.

Note: Most MongoDB driver clients will include the _id field and generate an ObjectId before sending the insert
operation to MongoDB; however, if the client sends a document without an _id field, the mongod (page 603) will
add the _id field and generate the ObjectId.

2.1. mongo Shell Methods 67


MongoDB Reference Manual, Release 3.0.7

Update If the document contains an _id field, then the save() (page 67) method is equivalent to an update with
the upsert option (page 72) set to true and the query predicate on the _id field.

Examples

Save a New Document without Specifying an _id Field In the following example, save() (page 67) method
performs an insert since the document passed to the method does not contain the _id field:
[Link]( { item: "book", qty: 40 } )

During the insert, the shell will create the _id field with a unique
[Link] value, as verified by the inserted
document:
{ "_id" : ObjectId("50691737d386d8fadbd6b01d"), "item" : "book", "qty" : 40 }

The ObjectId values are specific to the machine and time when the operation is run. As such, your values may
differ from those in the example.

Save a New Document Specifying an _id Field In the following example, save() (page 67) performs an update
with upsert:true since the document contains an _id field:
[Link]( { _id: 100, item: "water", qty: 30 } )

Because the _id field holds a value that does not exist in the collection, the update operation results in an insertion of
the document. The results of these operations are identical to an update() method with the upsert option (page 72) set
to true.
The operation results in the following new document in the products collection:
{ "_id" : 100, "item" : "water", "qty" : 30 }

Replace an Existing Document The products collection contains the following document:
{ "_id" : 100, "item" : "water", "qty" : 30 }

The save() (page 67) method performs an update with upsert:true since the document contains an _id field:
[Link]( { _id : 100, item : "juice" } )

Because the _id field holds a value that exists in the collection, the operation performs an update to replace the
document and results in the following document:
{ "_id" : 100, "item" : "juice" }

Override Default Write Concern The following operation to a replica set specifies a write concern of "w:
majority" with a wtimeout of 5000 milliseconds such that the method returns after the write propagates to a
majority of the voting replica set members or the method times out after 5 seconds.
Changed in version 3.0: In previous versions, majority referred to the majority of all members of the replica set.
[Link](
{ item: "envelopes", qty : 100, type: "Clasp" },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)

68 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

WriteResult Changed in version 2.6.


The save() (page 67) returns a WriteResult (page 207) object that contains the status of the insert or update
operation. See WriteResult for insert (page 55) and WriteResult for update (page 77) for details.

[Link]()

Definition
[Link](scale)
[Link](options)
Returns statistics about the collection. The method includes the following parameters:
param number scale Optional. The scale used in the output to display the sizes of items. By
default, output displays sizes in bytes. To display kilobytes rather than bytes, specify a scale
value of 1024.
Changed in version 3.0: Legacy parameter format. Mutually exclusive with options as a
document.
param document options Optional. Alternate option format. Mutually exclusive with scale as
a scalar parameter. The use of this format optionally allows suppression or filtering of index
details.
New in version 3.0.
The options document can contain the following fields and values:
field number scale Optional. The scale used in the output to display the sizes of items. By default,
output displays sizes in bytes. To display kilobytes rather than bytes, specify a scale value of
1024.
New in version 3.0.
field boolean indexDetails Optional. If true, [Link]() (page 69) returns
index details in addition to the collection stats.
Defaults to false.
New in version 3.0.
field document indexDetailsField Optional. If indexDetails is true, use
indexDetailsField to filter index details by specifying the index key. Use
getIndexes() (page 46) to discover index keys. You cannot use indexDetailsField
with indexDetailsName.
New in version 3.0.
field string indexDetailsName Optional. If indexDetails is true, use
indexDetailsName to filter index details by specifying the index name. Use
getIndexes() (page 46) to discover index names. You cannot use indexDetailsName
with indexDetailsField.
New in version 3.0.

Returns A document that contains statistics on the specified collection.

The stats() (page 69) method provides a wrapper around the database command collStats (page 369).

2.1. mongo Shell Methods 69


MongoDB Reference Manual, Release 3.0.7

Examples The following operation returns stats on the people collection:


[Link]()

The following operation returns stats on the orders collection, suppressing all index stats except for those of the
ascending index on the order_date field, and expressing sizes in kilobytes:
[Link]( { scale: 1024,
indexDetails: true,
indexKey: { order_date: 1 } } )

Additional Information Consider the collStats (page 369) document for an overview of the output of
[Link]() (page 69).

[Link]()

[Link]()
Returns The total amount of storage allocated to this collection for document storage. Provides
a wrapper around the storageSize (page 370) field of the collStats (page 369) (i.e.
[Link]() (page 69)) output.

[Link]()

[Link]()
Returns The total size in bytes of the data in the collection plus the size of every indexes on the
collection.

[Link]()

[Link]()
Returns The total size of all indexes for the collection. This method provides a wrapper
around the totalIndexSize (page 371) output of the collStats (page 369) (i.e.
[Link]() (page 69)) operation.

[Link]()

Definition
[Link](query, update, options)
Modifies an existing document or documents in a collection. The method can modify specific fields of an
existing document or documents or replace an existing document entirely, depending on the update parameter
(page 71).
By default, the update() (page 70) method updates a single document. Set the Multi Parameter (page 73) to
update all documents that match the query criteria.
The update() (page 70) method has the following form:
Changed in version 2.6.

70 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link](
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)

The update() (page 70) method takes the following parameters:


param document query The selection criteria for the update. The same query selectors (page 413)
as in the find() (page 35) method are available.
Changed in version 3.0: When you execute an update() (page 70) with upsert: true
and the query matches no existing document, MongoDB will refuse to insert a new document if
the query specifies conditions on the _id field using dot notation.
For more information and an example, see upsert:true with a Dotted _id Query (page 73).
param document update The modifications to apply. For details see Update Parameter (page 71).
param boolean upsert Optional. If set to true, creates a new document when no document
matches the query criteria. The default value is false, which does not insert a new document
when no match is found.
param boolean multi Optional. If set to true, updates multiple documents that meet the query
criteria. If set to false, updates one document. The default value is false. For additional
information, see Multi Parameter (page 73).
param document writeConcern Optional. A document expressing the write concern. Omit
to use the default write concern. See Safe Writes (page 71).
New in version 2.6.
Changed in version 2.6: The update() (page 70) method returns an object that contains the status of the
operation.
Returns A WriteResult (page 77) object that contains the status of the operation.

Behavior

Safe Writes Changed in version 2.6.


The update() (page 70) method uses the update (page 246) command, which uses the default write concern. To
specify a different write concern, include the writeConcern option in the options parameter. See Override Default
Write Concern (page 76) for an example.

Update Parameter The update() (page 70) method either modifies specific fields in existing documents or re-
places an existing document entirely.

Update Specific Fields If the <update> document contains update operator (page 464) modifiers, such as those
using the $set (page 469) modifier, then:
The <update> document must contain only update operator (page 464) expressions.
The update() (page 70) method updates only the corresponding fields in the document.

2.1. mongo Shell Methods 71


MongoDB Reference Manual, Release 3.0.7

To update an embedded document or an array as a whole, specify the replacement value for the field. To update
particular fields in an embedded document or in an array, use dot notation to specify the field.

Replace a Document Entirely If the <update> document contains only field:value expressions, then:
The update() (page 70) method replaces the matching document with the <update> document. The
update() (page 70) method does not replace the _id value. For an example, see Replace All Fields (page 74).
update() (page 70) cannot update multiple documents (page 73).

Upsert Option

Upsert Behavior If upsert is true and no document matches the query criteria, update() (page 70) inserts a
single document. The update creates the new document with either:
The fields and values of the <update> parameter if the <update> parameter contains only field and value
pairs, or
The fields and values of both the <query> and <update> parameters if the <update> parameter contains
update operator (page 464) expressions. The update creates a base document from the equality clauses in the
<query> parameter, and then applies the update expressions from the <update> parameter.
If upsert is true and there are documents that match the query criteria, update() (page 70) performs an update.
See also:
$setOnInsert (page 468)

Warning: To avoid inserting the same document more than once, only use upsert: true if the query fi
Use Unique Indexes
is uniquely indexed.

Given a collection named people where no documents have a name field that holds the value Andy. Consider when
multiple clients issue the following update with upsert: true at the same time:
[Link](
{ name: "Andy" },
{
name: "Andy",
rating: 1,
score: 1
},
{ upsert: true }
)

If all update() (page 70) operations complete the query portion before any client successfully inserts data, and
there is no unique index on the name field, then each update operation may result in an insert.
To prevent MongoDB from inserting the same document more than once, create a unique index on the name field.
With a unique index, if multiple applications issue the same update with upsert: true, exactly one update()
(page 70) would successfully insert a new document.
The remaining operations would either:
update the newly inserted document, or

72 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

fail when they attempted to insert a duplicate.


If the operation fails because of a duplicate index key error, applications may retry the operation which will
succeed as an update operation.

upsert:true with a Dotted _id Query When you execute an update() (page 70) with upsert: true
and the query matches no existing document, MongoDB will refuse to insert a new document if the query specifies
conditions on the _id field using dot notation.
This restriction ensures that the order of fields embedded in the _id document is well-defined and not bound to the
order specified in the query
If you attempt to insert a document in this way, MongoDB will raise an error.
For example, consider the following update operation. Since the update operation specifies upsert:true and the
query specifies conditions on the _id field using dot notation, then the update will result in an error when constructing
the document to insert.
[Link]( { "_id.name": "Robert Frost", "_id.uid": 0 },
{ "categories": ["poet", "playwright"] },
{ upsert: true } )

Multi Parameter If multi is set to true, the update() (page 70) method updates all documents that meet
the <query> criteria. The multi update operation may interleave with other operations, both read and/or write
operations. For unsharded collections, you can override this behavior with the $isolated (page 496) operator,
which isolates the update operation and disallows yielding during the operation. This isolates the update so that no
client can see the updated documents until they are all processed, or an error stops the update operation.
If the <update> (page 71) document contains only field:value expressions, then update() (page 70) cannot
update multiple documents.
For an example, see Update Multiple Documents (page 75).

Sharded Collections All update() (page 70) operations for a sharded collection that specify the multi:
false option must include the shard key or the _id field in the query specification. update() (page 70) op-
erations specifying multi: false in a sharded collection without the shard key or the _id field return an error.
See also:
findAndModify() (page 41)

Examples

Update Specific Fields To update specific fields in a document, use update operators (page 464) in the <update>
parameter.
For example, given a books collection with the following document:
{
_id: 1,
item: "TBD",
stock: 0,
info: { publisher: "1111", pages: 430 },
tags: [ "technology", "computer" ],
ratings: [ { by: "ijk", rating: 4 }, { by: "lmn", rating: 5 } ],
reorder: false
}

2.1. mongo Shell Methods 73


MongoDB Reference Manual, Release 3.0.7

The following operation uses:


the $inc (page 464) operator to increment the stock field; and
the $set (page 469) operator to replace the value of the item field, the publisher field in the info
embedded document, the tags field, and the second element in the ratings array.
[Link](
{ _id: 1 },
{
$inc: { stock: 5 },
$set: {
item: "ABC123",
"[Link]": "2222",
tags: [ "software" ],
"ratings.1": { by: "xyz", rating: 3 }
}
}
)

The updated document is the following:


{
"_id" : 1,
"item" : "ABC123",
"stock" : 5,
"info" : { "publisher" : "2222", "pages" : 430 },
"tags" : [ "software" ],
"ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "xyz", "rating" : 3 } ],
"reorder" : false
}

See also:
$set (page 469), $inc (page 464), Update Operators (page 464), dot notation

Remove Fields The following operation uses the $unset (page 470) operator to remove the tags field:
[Link]( { _id: 1 }, { $unset: { tags: 1 } } )

See also:
$unset (page 470), $rename (page 467), Update Operators (page 464)

Replace All Fields Given the following document in the books collection:
{
_id: 2,
item: "XYZ123",
stock: 15,
info: { publisher: "5555", pages: 150 },
tags: [ ],
ratings: [ { by: "xyz", rating: 5, comment: "ratings and reorder will go away after update"} ],
reorder: false
}

The following operation passes an <update> document that contains only field and value pairs. The <update>
document completely replaces the original document except for the _id field.

74 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link](
{ item: "XYZ123" },
{
item: "XYZ123",
stock: 10,
info: { publisher: "2255", pages: 150 },
tags: [ "baking", "cooking" ]
}
)

The updated document contains only the fields from the replacement document and the _id field. That is, the fields
ratings and reorder no longer exist in the updated document since the fields were not in the replacement docu-
ment.
{
"_id" : 2,
"item" : "XYZ123",
"stock" : 10,
"info" : { "publisher" : "2255", "pages" : 150 },
"tags" : [ "baking", "cooking" ]
}

Insert a New Document if No Match Exists The following update sets the upsert (page 72) option to true so
that update() (page 70) creates a new document in the books collection if no document matches the <query>
parameter:
[Link](
{ item: "ZZZ135" },
{
item: "ZZZ135",
stock: 5,
tags: [ "database" ]
},
{ upsert: true }
)

If no document matches the <query> parameter, the update operation inserts a document with only the fields and
values of the <update> document and a new unique ObjectId for the _id field:
{
"_id" : ObjectId("542310906694ce357ad2a1a9"),
"item" : "ZZZ135",
"stock" : 5,
"tags" : [ "database" ]
}

For more information on upsert option and the inserted document, Upsert Option (page 72).

Update Multiple Documents To update multiple documents, set the multi option to true. For example, the
following operation updates all documents where stock is less than or equal to 10:
[Link](
{ stock: { $lte: 10 } },
{ $set: { reorder: true } },
{ multi: true }
)

2.1. mongo Shell Methods 75


MongoDB Reference Manual, Release 3.0.7

If the reorder field does not exist in the matching document(s), the $set (page 469) operator will add the field
with the specified value. See $set (page 469) for more information.

Override Default Write Concern The following operation on a replica set specifies a write concern of "w:
majority" with a wtimeout of 5000 milliseconds such that the method returns after the write propagates to a
majority of the voting replica set members or the method times out after 5 seconds.
Changed in version 3.0: In previous versions, majority referred to the majority of all members of the replica set.
[Link](
{ stock: { $lte: 10 } },
{ $set: { reorder: true } },
{
multi: true,
writeConcern: { w: "majority", wtimeout: 5000 }
}
)

Combine the upsert and multi Options Given a books collection that includes the following documents:
{
_id: 5,
item: "EFG222",
stock: 18,
info: { publisher: "0000", pages: 70 },
reorder: true
}
{
_id: 6,
item: "EFG222",
stock: 15,
info: { publisher: "1111", pages: 72 },
reorder: true
}

The following operation specifies both the multi option and the upsert option. If matching documents exist, the
operation updates all matching documents. If no matching documents exist, the operation inserts a new document.
[Link](
{ item: "EFG222" },
{ $set: { reorder: false, tags: [ "literature", "translated" ] } },
{ upsert: true, multi: true }
)

The operation updates all matching documents and results in the following:
{
"_id" : 5,
"item" : "EFG222",
"stock" : 18,
"info" : { "publisher" : "0000", "pages" : 70 },
"reorder" : false,
"tags" : [ "literature", "translated" ]
}
{
"_id" : 6,
"item" : "EFG222",
"stock" : 15,

76 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

"info" : { "publisher" : "1111", "pages" : 72 },


"reorder" : false,
"tags" : [ "literature", "translated" ]
}

If the collection had no matching document, the operation would result in the insertion of a document using the fields
from both the <query> and the <update> specifications:
{
"_id" : ObjectId("5423200e6694ce357ad2a1ac"),
"item" : "EFG222",
"reorder" : false,
"tags" : [ "literature", "translated" ]
}

For more information on upsert option and the inserted document, Upsert Option (page 72).

WriteResult Changed in version 2.6.

Successful Results The update() (page 70) method returns a WriteResult (page 207) object that contains the
status of the operation. Upon success, the WriteResult (page 207) object contains the number of documents that
matched the query condition, the number of documents inserted by the update, and the number of documents modified:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

See
[Link] (page 207), [Link] (page 207), [Link]
(page 207)

Write Concern Errors If the update() (page 70) method encounters write concern errors, the results include the
[Link] (page 207) field:
WriteResult({
"nMatched" : 1,
"nUpserted" : 0,
"nModified" : 1,
"writeConcernError" : {
"code" : 64,
"errmsg" : "waiting for replication timed out at shard-a"
}
})

See also:
[Link]() (page 208)

Errors Unrelated to Write Concern If the update() (page 70) method encounters a non-write concern error, the
results include the [Link] (page 207) field:
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {

2.1. mongo Shell Methods 77


MongoDB Reference Manual, Release 3.0.7

"code" : 7,
"errmsg" : "could not contact primary for replica set shard-a"
}
})

See also:
[Link]() (page 208)

Additional Resources
Quick Reference Cards5

[Link]()

Description
[Link](full)
Validates a collection. The method scans a collections data structures for correctness and returns a single
document that describes the relationship between the logical collection and the physical representation of the
data.
The validate() (page 78) method has the following parameter:
param boolean full Optional. Specify true to enable a full validation and to return full statis-
tics. MongoDB disables full validation by default because it is a potentially resource-intensive
operation.
The validate() (page 78) method output provides an in-depth view of how the collection uses storage. Be
aware that this command is potentially resource intensive and may impact the performance of your MongoDB
instance.
The validate() (page 78) method is a wrapper around the validate (page 379) database command.
See also:
validate (page 379)
5 [Link]

78 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

2.1.2 Cursor

Cursor Methods

Name Description
[Link]() Adds special wire protocol flags that modify the behavior of the query.
(page 80)
[Link]() Controls the number of documents MongoDB will return to the client in a single
(page 80) network message.
[Link]() Returns the total number of documents in a cursor.
(page 81)
[Link]() Reports on the query execution plan, including index use, for a cursor.
(page 83)
[Link]() Applies a JavaScript function for every document in a cursor.
(page 84)
[Link]() Returns true if the cursor has documents and can be iterated.
(page 85)
[Link]() Forces MongoDB to use a specific index for a query.
(page 85)
[Link]() Returns the number of documents remaining in a cursor.
(page 86)
[Link]() Constrains the size of a cursors result set.
(page 86)
[Link]() Applies a function to each document in a cursor and collects the return values in an
(page 87) array.
[Link]() Specifies a cumulative time limit in milliseconds for processing operations on a
(page 87) cursor.
[Link]() Specifies an exclusive upper index bound for a cursor. For use with
(page 87) [Link]() (page 85)
[Link]() Specifies an inclusive lower index bound for a cursor. For use with
(page 89) [Link]() (page 85)
[Link]() Returns the next document in a cursor.
(page 91)
Returns the number of documents left in the current cursor batch.
[Link]()
(page 91)
[Link]() Configures the cursor to display results in an easy-to-read format.
(page 91)
[Link]() Specifies a read preference to a cursor to control how the client directs queries to a
(page 92) replica set.
[Link]()Returns a cursor with modified documents that include the on-disk location of the
(page 92) document.
[Link]() Returns a count of the documents in the cursor after applying skip() (page 93) and
(page 93) limit() (page 86) methods.
[Link]() Returns a cursor that begins returning results only after passing or skipping a number
(page 93) of documents.
[Link]() Forces the cursor to use the index on the _id field. Ensures that the cursor returns
(page 94) each document, with regards to the value of the _id field, only once.
[Link]() Returns results ordered according to a sort specification.
(page 94)
[Link]() Returns an array that contains all documents returned by the cursor.
(page 98)

2.1. mongo Shell Methods 79


MongoDB Reference Manual, Release 3.0.7

[Link]()

Definition
[Link](flag)
Adds OP_QUERY wire protocol flags, such as the tailable flag, to change the behavior of queries.
The [Link]() (page 80) method has the following parameter:
param flag flag OP_QUERY wire protocol flag. For the mongo (page 632) shell, you can use the
cursor flags listed below. For the driver-specific list, see your driver documentation.

Flags The mongo (page 632) shell provides several additional cursor flags to modify the behavior of the cursor.
Flag Description
Sets the cursor not to close once the last data is received,
[Link]
allowing the query to continue returning data added after
the initial results were exhausted.
Allows querying of a replica slave.
[Link]

Prevents the server from timing out idle cursors.


[Link]

For use with .. data:: [Link]; sets the


[Link]
cursor to block and await data for a while rather than
returning no data. The cursor will return no data once
the timeout has expired.
Sets the cursor to return all data returned by the query at
[Link]
once rather than splitting the results into batches.
Sets the cursor to return partial data from a query against
[Link]
a sharded cluster in which some shards do not respond
rather than throwing an error.

Example The following example adds the [Link] flag and the
[Link] flag to ensure that the query returns a tailable cursor. The sequence cre-
ates a cursor that will wait for few seconds after returning the full result set so that it can capture and return additional
data added during the query:
var t = [Link];
var cursor = [Link]().addOption([Link]).
addOption([Link])

Warning: Adding incorrect wire protocol flags can cause problems and/or extra server load.

[Link]()

Definition
[Link](size)
Specifies the number of documents to return in each batch of the response from the MongoDB instance. In most
cases, modifying the batch size will not affect the user or the application, as the mongo (page 632) shell and
most drivers return results as if MongoDB returned a single batch.
The batchSize() (page 80) method takes the following parameter:

80 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

param integer size The number of documents to return per batch. Do not use a batch size of 1.

Note: Specifying 1 or a negative number is analogous to using the limit() (page 86) method.

Example The following example sets the batch size for the results of a query (i.e. find() (page 35)) to 10. The
batchSize() (page 80) method does not change the output in the mongo (page 632) shell, which, by default,
iterates over the first 20 documents.
[Link]().batchSize(10)

[Link]()

Definition
[Link]()
Counts the number of documents referenced by a cursor. Append the count() (page 81) method to a find()
(page 35) query to return the number of matching documents. The operation does not perform the query but
instead counts the results that would be returned by the query.
Changed in version 2.6: MongoDB supports the use of hint() (page 85) with count() (page 81). See
Specify the Index to Use (page 83) for an example.
The count() (page 81) method has the following prototype form:
[Link](<query>).count()

The count() (page 81) method has the following parameter:


param boolean applySkipLimit Optional. Specifies whether to consider the effects of the
[Link]() (page 93) and [Link]() (page 86) methods in the count. By
default, the count() (page 81) method ignores the effects of the [Link]() (page 93)
and [Link]() (page 86). Set applySkipLimit to true to consider the effect of
these methods.
MongoDB also provides an equivalent [Link]() (page 23) as an alternative to the
[Link](<query>).count() construct.
See also:
[Link]() (page 93)

Behavior

Sharded Clusters On a sharded cluster, count() (page 81) can result in an inaccurate count if orphaned docu-
ments exist or if a chunk migration is in progress.
To avoid these situations, on a sharded cluster, use the $group (page 508) stage of the
[Link]() (page 20) method to $sum (page 565) the documents. For example, the
following operation counts the documents in a collection:
[Link](
[
{ $group: { _id: null, count: { $sum: 1 } } }
]
)

2.1. mongo Shell Methods 81


MongoDB Reference Manual, Release 3.0.7

To get a count of documents that match a query condition, include the $match (page 501) stage as well:
[Link](
[
{ $match: <query condition> },
{ $group: { _id: null, count: { $sum: 1 } } }
]
)

See Perform a Count (page 502) for an example.

Index Use Consider a collection with the following index:


{ a: 1, b: 1 }

When performing a count, MongoDB can return the count using only the index if:
the query can use an index,
the query only contains conditions on the keys of the index, and
the query predicates access a single contiguous range of index keys.
For example, the following operations can return the count using only the index:
[Link]( { a: 5, b: 5 } ).count()
[Link]( { a: { $gt: 5 } } ).count()
[Link]( { a: 5, b: { $gt: 10 } } ).count()

If, however, the query can use an index but the query predicates do not access a single contiguous range of index keys
or the query also contains conditions on fields outside the index, then in addition to using the index, MongoDB must
also read the documents to return the count.
[Link]( { a: 5, b: { $in: [ 1, 2, 3 ] } } ).count()
[Link]( { a: { $gt: 5 }, b: 5 } ).count()
[Link]( { a: 5, b: 5, c: 5 } ).count()

In such cases, during the initial read of the documents, MongoDB pages the documents into memory such that subse-
quent calls of the same count operation will have better performance.

Examples The following are examples of the count() (page 81) method.

Count All Documents The following operation counts the number of all documents in the orders collection:
[Link]().count()

Count Documents That Match a Query The following operation counts the number of the documents in the
orders collection with the field ord_dt greater than new Date(01/01/2012):
[Link]( { ord_dt: { $gt: new Date('01/01/2012') } } ).count()

Limit Documents in Count The following operation counts the number of the documents in the orders collection
with the field ord_dt greater than new Date(01/01/2012) taking into account the effect of the limit(5):
[Link]( { ord_dt: { $gt: new Date('01/01/2012') } } ).limit(5).count(true)

82 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Specify the Index to Use The following operation uses the index named "status_1", which has the index key
specification of { status: 1 }, to return a count of the documents in the orders collection with the field
ord_dt greater than new Date(01/01/2012) and the status field is equal to "D":
[Link](
{ ord_dt: { $gt: new Date('01/01/2012') }, status: "D" }
).hint( "status_1" ).count()

[Link]()

Definition
[Link](verbosity)
Changed in version 3.0: The parameter to the method and the output format have changed in 3.0.
Provides information on the query plan for the [Link]() (page 35) method.
The explain() (page 83) method has the following form:
[Link]().explain()

The explain() (page 83) method has the following parameter:


param string verbose Optional. Specifies the verbosity mode for the explain output. The
mode affects the behavior of explain() and determines the amount of information
to return. The possible modes are: "queryPlanner", "executionStats", and
"allPlansExecution".
Default mode is "queryPlanner".
For backwards compatibility with earlier versions of [Link]() (page 83), Mon-
goDB interprets true as "allPlansExecution" and false as "queryPlanner".
For more information on the modes, see Verbosity Modes (page 83).
Changed in version 3.0.
The explain() (page 83) method returns a document with the query plan and, optionally, the execution
statistics.

Behavior

Verbosity Modes The behavior of [Link]() (page 83) and the amount of information returned depend
on the verbosity mode.

queryPlanner Mode By default, [Link]() (page 83) runs in queryPlanner verbosity mode.
MongoDB runs the query optimizer to choose the winning plan for the operation under evaluation.
[Link]() (page 83) returns the queryPlanner (page 767) information for the evaluated method.

executionStats Mode MongoDB runs the query optimizer to choose the winning plan, executes the
winning plan to completion, and returns statistics describing the execution of the winning plan.
[Link]() (page 83) returns the queryPlanner (page 767) and executionStats (page 768) in-
formation for the evaluated method. However, executionStats (page 768) does not provide query execution
information for the rejected plans.

2.1. mongo Shell Methods 83


MongoDB Reference Manual, Release 3.0.7

allPlansExecution Mode MongoDB runs the query optimizer to choose the winning plan and executes
the winning plan to completion. In "allPlansExecution" mode, MongoDB returns statistics describing the
execution of the winning plan as well as statistics for the other candidate plans captured during plan selection.
[Link]() (page 83) returns the queryPlanner (page 767) and executionStats (page 768) in-
formation for the evaluated method. The executionStats (page 768) includes the completed query execution
information for the winning plan.
If the query optimizer considered more than one plan, executionStats (page 768) information also includes the
partial execution information captured during the plan selection phase for both the winning and rejected candidate
plans.

[Link]().find() [Link]().find() is similar to


[Link]().explain() (page 83) with the following key differences:
The [Link]().find() construct allows for the additional chaining of query modi-
fiers. For list of query modifiers, see [Link]().find().help() (page 33).
The [Link]().find() returns a cursor, which requires a call to .next(), or its
alias .finish(), to return the explain() results.
See [Link]() (page 32) for more information.

Example The following example runs [Link]() (page 83) in executionStats (page 33) verbosity
mode to return the query planning and execution information for the specified [Link]() (page 35)
operation:
[Link](
{ quantity: { $gt: 50 }, category: "apparel" }
).explain("executionStats")

Output [Link]() (page 83) operations can return information regarding:


queryPlanner (page 766), which details the plan selected by the query optimizer and lists the rejected
plans;
executionStats (page 767), which details the execution of the winning plan and the rejected plans; and
serverInfo (page 769), which provides information on the MongoDB instance.
The verbosity mode (i.e. queryPlanner, executionStats, allPlansExecution) determines whether the
results include executionStats (page 767) and whether executionStats (page 767) includes data captured during plan
selection.
For details on the output, see Explain Results (page 766).
For a mixed version sharded cluster with version 3.0 mongos (page 622) and at least one 2.6 mongod
(page 603) shard, when you run [Link]() (page 83) in a version 3.0 mongo (page 632) shell,
[Link]() (page 83) will retry with the $explain (page 573) operator to return results in the 2.6
format.

[Link]()

Description

84 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link](function)
Iterates the cursor to apply a JavaScript function to each document from the cursor.
The forEach() (page 84) method has the following prototype form:
[Link]().forEach(<function>)

The forEach() (page 84) method has the following parameter:


param JavaScript function A JavaScript function to apply to each document from the cursor. The
<function> signature includes a single argument that is passed the current document to pro-
cess.

Example The following example invokes the forEach() (page 84) method on the cursor returned by find()
(page 35) to print the name of each user in the collection:
[Link]().forEach( function(myDoc) { print( "user: " + [Link] ); } );

See also:
[Link]() (page 87) for similar functionality.

[Link]()

[Link]()
Returns Boolean.
[Link]() (page 85) returns true if the cursor returned by the [Link]()
(page 35) query can iterate further to return more documents.

[Link]()

Definition
[Link](index)
Call this method on a query to override MongoDBs default index selection and query optimization
process. Use [Link]() (page 46) to return the list of current indexes on a col-
lection.
The [Link]() (page 85) method has the following parameter:
param string, document index The index to hint or force MongoDB to use when performing the
query. Specify the index either by the index name or by the index specification document.

Behavior When an index filter exists for the query shape, MongoDB ignores the hint() (page 85).
You cannot use hint() (page 85) if the query includes a $text (page 432) query expression.

Example The following example returns all documents in the collection named users using the index on the age
field.
[Link]().hint( { age: 1 } )

You can also specify the index using the index name:

2.1. mongo Shell Methods 85


MongoDB Reference Manual, Release 3.0.7

[Link]().hint( "age_1" )

See also:
[Link]
[Link]
[Link]
index-filters
$hint (page 574)

[Link]()

Definition
[Link]()
Counts the number of documents remaining in a cursor.
itcount() (page 86) is similar to [Link]() (page 81), but actually executes the query on an
existing iterator, exhausting its contents in the process.
The itcount() (page 86) method has the following prototype form:
[Link](<query>).itcount()

See also:
[Link]() (page 81)

[Link]()

Definition
[Link]()
Use the limit() (page 86) method on a cursor to specify the maximum number of documents the cursor will
return. limit() (page 86) is analogous to the LIMIT statement in a SQL database.

Note: You must apply limit() (page 86) to the cursor before retrieving any documents from the database.

Use limit() (page 86) to maximize performance and prevent MongoDB from returning more results than
required for processing.

Behavior

Supported Values The behavior of limit() (page 86) is undefined for values less than -231 and greater than 231 .

Zero Value A limit() (page 86) value of 0 (i.e. .limit(0) (page 86)) is equivalent to setting no limit.

Negative Values A negative limit is similar to a positive limit but closes the cursor after returning a single batch of
results. As such, with a negative limit, if the limited result set does not fit into a single batch, the number of documents
received will be less than the specified limit. By passing a negative limit, the client indicates to the server that it will
not ask for a subsequent batch via getMore.

86 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link]()

[Link](function)
Applies function to each document visited by the cursor and collects the return values from successive
application into an array.
The [Link]() (page 87) method has the following parameter:
param function function A function to apply to each document visited by the cursor.

Example
[Link]().map( function(u) { return [Link]; } );

See also:
[Link]() (page 84) for similar functionality.

[Link]()

Definition New in version 2.6.


[Link](<time limit>)
Specifies a cumulative time limit in milliseconds for processing operations on a cursor.
The maxTimeMS() (page 87) method has the following parameter:
param integer milliseconds Specifies a cumulative time limit in milliseconds for processing oper-
ations on the cursor.

Important: maxTimeMS() (page 87) is not related to the NoCursorTimeout query flag. maxTimeMS()
(page 87) relates to processing time, while NoCursorTimeout relates to idle time. A cursors idle time does not
contribute towards its processing time.

Behaviors MongoDB targets operations for termination if the associated cursor exceeds its allotted time limit.
MongoDB terminates operations that exceed their allotted time limit, using the same mechanism as [Link]()
(page 122). MongoDB only terminates an operation at one of its designated interrupt points.
MongoDB does not count network latency towards a cursors time limit.
Queries that generate multiple batches of results continue to return batches until the cursor exceeds its allotted time
limit.

Examples
Example
The following query specifies a time limit of 50 milliseconds:
[Link]({description: /August [0-9]+, 1969/}).maxTimeMS(50)

[Link]()

Definition

2.1. mongo Shell Methods 87


MongoDB Reference Manual, Release 3.0.7

[Link]()
Specifies the exclusive upper bound for a specific index in order to constrain the results of find() (page 35).
max() (page 87) provides a way to specify an upper bound on compound key indexes.
The max() (page 87) method has the following parameter:
param document indexBounds The exclusive upper bound for the index keys.
The indexBounds parameter has the following prototype form:
{ field1: <max value>, field2: <max value2> ... fieldN:<max valueN> }

The fields correspond to all the keys of a particular index in order. You can explicitly specify the particular
index with the hint() (page 85) method. Otherwise, mongod (page 603) selects the index using the fields in
the indexBounds; however, if multiple indexes exist on same fields with different sort orders, the selection
of the index may be ambiguous.
See also:
min() (page 89).
max() (page 87) exists primarily to support the mongos (page 622) (sharding) process, and is a shell wrapper
around the query modifier $max (page 575).

Behavior

Interaction with Index Selection Because max() (page 87) requires an index on a field, and forces the query to
use this index, you may prefer the $lt (page 417) operator for the query if possible. Consider the following example:
[Link]( { _id: 7 } ).max( { price: 1.39 } )

The query will use the index on the price field, even if the index on _id may be better.

Index Bounds If you use max() (page 87) with min() (page 89) to specify a range, the index bounds specified in
min() (page 89) and max() (page 87) must both refer to the keys of the same index.

max() without min() The min and max operators indicate that the system should avoid normal query planning.
Instead they construct an index scan where the index bounds are explicitly specified by the values given in min and
max.

Warning: If one of the two boundaries is not specified, the query plan will be an index scan that is unbounded
on one side. This may degrade performance compared to a query containing neither operator, or one that uses both
operators to more tightly constrain the index scan.

Example This example assumes a collection named products that holds the following documents:
{ "_id" : 6, "item" : "apple", "type" : "cortland", "price" : 1.29 }
{ "_id" : 2, "item" : "apple", "type" : "fuji", "price" : 1.99 }
{ "_id" : 1, "item" : "apple", "type" : "honey crisp", "price" : 1.99 }
{ "_id" : 3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }
{ "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }
{ "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }
{ "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }
{ "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 }
{ "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }
{ "_id" : 8, "item" : "orange", "type" : "valencia", "price" : 0.99 }

88 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

The collection has the following indexes:


{ "_id" : 1 }
{ "item" : 1, "type" : 1 }
{ "item" : 1, "type" : -1 }
{ "price" : 1 }

Using the ordering of { item: 1, type: 1 } index, max() (page 87) limits the query to the docu-
ments that are below the bound of item equal to apple and type equal to jonagold:
[Link]().max( { item: 'apple', type: 'jonagold' } ).hint( { item: 1, type: 1 } )

The query returns the following documents:


{ "_id" : 6, "item" : "apple", "type" : "cortland", "price" : 1.29 }
{ "_id" : 2, "item" : "apple", "type" : "fuji", "price" : 1.99 }
{ "_id" : 1, "item" : "apple", "type" : "honey crisp", "price" : 1.99 }

If the query did not explicitly specify the index with the hint() (page 85) method, it is ambiguous as to whether
mongod (page 603) would select the { item: 1, type: 1 } index ordering or the { item: 1,
type: -1 } index ordering.
Using the ordering of the index { price: 1 }, max() (page 87) limits the query to the documents that are
below the index key bound of price equal to 1.99 and min() (page 89) limits the query to the documents
that are at or above the index key bound of price equal to 1.39:
[Link]().min( { price: 1.39 } ).max( { price: 1.99 } ).hint( { price: 1 } )

The query returns the following documents:


{ "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 }

[Link]()

Definition
[Link]()
Specifies the inclusive lower bound for a specific index in order to constrain the results of find() (page 35).
min() (page 89) provides a way to specify lower bounds on compound key indexes.
The min() (page 89) method has the following parameter:
param document indexBounds The inclusive lower bound for the index keys.
The indexBounds parameter has the following prototype form:
{ field1: <min value>, field2: <min value2>, fieldN:<min valueN> }

The fields correspond to all the keys of a particular index in order. You can explicitly specify the particular
index with the hint() (page 85) method. Otherwise, MongoDB selects the index using the fields in the
indexBounds; however, if multiple indexes exist on same fields with different sort orders, the selection of the
index may be ambiguous.
See also:
max() (page 87).
min() (page 89) exists primarily to support the mongos (page 622) process, and is a shell wrapper around the
query modifier $min (page 576).

2.1. mongo Shell Methods 89


MongoDB Reference Manual, Release 3.0.7

Behaviors

Interaction with Index Selection Because min() (page 89) requires an index on a field, and forces the query to use
this index, you may prefer the $gte (page 416) operator for the query if possible. Consider the following example:
[Link]( { _id: 7 } ).min( { price: 1.39 } )

The query will use the index on the price field, even if the index on _id may be better.

Index Bounds If you use min() (page 89) with max() (page 87) to specify a range, the index bounds specified in
min() (page 89) and max() (page 87) must both refer to the keys of the same index.

min() without max() The min and max operators indicate that the system should avoid normal query planning.
Instead they construct an index scan where the index bounds are explicitly specified by the values given in min and
max.

Warning: If one of the two boundaries is not specified, the query plan will be an index scan that is unbounded
on one side. This may degrade performance compared to a query containing neither operator, or one that uses both
operators to more tightly constrain the index scan.

Example This example assumes a collection named products that holds the following documents:
{ "_id" : 6, "item" : "apple", "type" : "cortland", "price" : 1.29 }
{ "_id" : 2, "item" : "apple", "type" : "fuji", "price" : 1.99 }
{ "_id" : 1, "item" : "apple", "type" : "honey crisp", "price" : 1.99 }
{ "_id" : 3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }
{ "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }
{ "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }
{ "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }
{ "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 }
{ "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }
{ "_id" : 8, "item" : "orange", "type" : "valencia", "price" : 0.99 }

The collection has the following indexes:


{ "_id" : 1 }
{ "item" : 1, "type" : 1 }
{ "item" : 1, "type" : -1 }
{ "price" : 1 }

Using the ordering of the { item: 1, type: 1 } index, min() (page 89) limits the query to the
documents that are at or above the index key bound of item equal to apple and type equal to jonagold,
as in the following:
[Link]().min( { item: 'apple', type: 'jonagold' } ).hint( { item: 1, type: 1 } )

The query returns the following documents:


{ "_id" : 3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }
{ "_id" : 4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }
{ "_id" : 5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }
{ "_id" : 7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }
{ "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 }
{ "_id" : 9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }
{ "_id" : 8, "item" : "orange", "type" : "valencia", "price" : 0.99 }

90 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

If the query did not explicitly specify the index with the hint() (page 85) method, it is ambiguous as to whether
mongod (page 603) would select the { item: 1, type: 1 } index ordering or the { item: 1,
type: -1 } index ordering.
Using the ordering of the index { price: 1 }, min() (page 89) limits the query to the documents that
are at or above the index key bound of price equal to 1.39 and max() (page 87) limits the query to the
documents that are below the index key bound of price equal to 1.99:
[Link]().min( { price: 1.39 } ).max( { price: 1.99 } ).hint( { price: 1 } )

The query returns the following documents:


{ "_id" : 10, "item" : "orange", "type" : "navel", "price" : 1.39 }

[Link]()

[Link]()
Returns The next document in the cursor returned by the [Link]() (page 35)
method. See [Link]() (page 85) related functionality.

[Link]()

[Link]()
[Link]() (page 91) returns the number of documents remaining in the current batch.
The MongoDB instance returns response in batches. To retrieve all the documents from a cursor may require
multiple batch responses from the MongoDB instance. When there are no more documents remaining in the
current batch, the cursor will retrieve another batch to get more documents until the cursor exhausts.

[Link]()

Definition
[Link]()
Configures the cursor to display results in an easy-to-read format.
The pretty() (page 91) method has the following prototype form:
[Link](<query>).pretty()

Examples Consider the following document:


[Link]({
"_id" : ObjectId("54f612b6029b47909a90ce8d"),
"title" : "A Tale of Two Cities",
"text" : "It was the best of times, it was the worst of times, it was the age of wisdom, it was t
"authorship" : "Charles Dickens"})

By default, [Link]() (page 35) returns data in a dense format:


[Link]()
{ "_id" : ObjectId("54f612b6029b47909a90ce8d"), "title" : "A Tale of Two Cities", "text" : "It was th

By using [Link]() (page 91) you can set the cursor to return data in a format that is easier for humans to
parse:

2.1. mongo Shell Methods 91


MongoDB Reference Manual, Release 3.0.7

[Link]().pretty()
{
"_id" : ObjectId("54f612b6029b47909a90ce8d"),
"title" : "A Tale of Two Cities",
"text" : "It was the best of times, it was the worst of times, it was the age of wisdom, it was t
"authorship" : "Charles Dickens"
}

[Link]()

Definition
[Link](mode, tagSet)
Append readPref() (page 92) to a cursor to control how the client routes the query to members of the replica
set.
param string mode One of the following read preference modes: primary,
primaryPreferred, secondary, secondaryPreferred, or nearest
param array tagSet Optional. A tag set used to specify custom read preference modes. For details,
see replica-set-read-preference-tag-sets.

Note: You must apply readPref() (page 92) to the cursor before retrieving any documents from the
database.

[Link]()

[Link]()
Modifies the output of a query by adding a field $diskLoc to matching documents. $diskLoc contains disk
location information and has the form:
"$diskLoc": {
"file": <int>,
"offset": <int>
}

[Link]() (page 92) method is a wrapper around $showDiskLoc (page 578).


Returns A modified cursor object that contains documents with appended information that describes
the on-disk location of the document.

Example The following operation appends the showDiskLoc() (page 92) method to the
[Link]() (page 35) method in order to include in the matching documents the disk loca-
tion information:
[Link]( { a: 1 } ).showDiskLoc()

The operation returns the following documents, which includes the $diskLoc field:
{
"_id" : ObjectId("53908ccb18facd50a75bfbac"),
"a" : 1,
"b" : 1,
"$diskLoc" : { "file" : 0, "offset" : 16195760 }
}

92 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

{
"_id" : ObjectId("53908cd518facd50a75bfbad"),
"a" : 1,
"b" : 2,
"$diskLoc" : { "file" : 0, "offset" : 16195824 }
}

The projection can also access the added field $diskLoc, as in the following example:
[Link]( { a: 1 }, { $diskLoc: 1 } ).showDiskLoc()

The operation returns just the _id field and the $diskLoc field in the matching documents:
{
"_id" : ObjectId("53908ccb18facd50a75bfbac"),
"$diskLoc" : { "file" : 0, "offset" : 16195760 }
}
{
"_id" : ObjectId("53908cd518facd50a75bfbad"),
"$diskLoc" : { "file" : 0, "offset" : 16195824 }
}

See also:
$showDiskLoc (page 578) for related functionality.

[Link]()

[Link]()
Returns A count of the number of documents that match the [Link]()
(page 35) query after applying any [Link]() (page 93) and [Link]()
(page 86) methods.

[Link]()

[Link]()
Call the [Link]() (page 93) method on a cursor to control where MongoDB begins returning results.
This approach may be useful in implementing paged results.

Note: You must apply [Link]() (page 93) to the cursor before retrieving any documents from the
database.

Consider the following JavaScript function as an example of the skip function:


function printStudents(pageNumber, nPerPage) {
print("Page: " + pageNumber);
[Link]().skip(pageNumber > 0 ? ((pageNumber-1)*nPerPage) : 0).limit(nPerPage).forEa
}

The [Link]() (page 93) method is often expensive because it requires the server to walk from the
beginning of the collection or index to get the offset or skip position before beginning to return results. As the
offset (e.g. pageNumber above) increases, [Link]() (page 93) will become slower and more CPU
intensive. With larger collections, [Link]() (page 93) may become IO bound.

2.1. mongo Shell Methods 93


MongoDB Reference Manual, Release 3.0.7

Consider using range-based pagination for these kinds of tasks. That is, query for a range of objects, using logic
within the application to determine the pagination rather than the database itself. This approach features better
index utilization, if you do not need to easily jump to a specific page.

[Link]()

[Link]()
Append the snapshot() (page 94) method to a cursor to toggle the snapshot mode. This ensures that the
query will not return a document multiple times, even if intervening write operations result in a move of the
document due to the growth in document size.

Warning:
You must apply snapshot() (page 94) to the cursor before retrieving any documents from the
database.
You can only use snapshot() (page 94) with unsharded collections.

The snapshot() (page 94) does not guarantee isolation from insertion or deletions.
The snapshot() (page 94) traverses the index on the _id field. As such, snapshot() (page 94) cannot
be used with sort() (page 94) or hint() (page 85).
Queries with results of less than 1 megabyte are effectively implicitly snapshotted.

[Link]()

Definition
[Link](sort)
Specifies the order in which the query returns matching documents. You must apply sort() (page 94) to the
cursor before retrieving any documents from the database.
The sort() (page 94) method has the following parameter:
param document sort A document that defines the sort order of the result set.
The sort parameter contains field and value pairs, in the following form:
{ field: value }

The sort document can specify ascending or descending sort on existing fields (page 94) or sort on computed
metadata (page 95).

Behaviors

Result Ordering Unless you specify the sort() (page 94) method or use the $near (page 442) operator, Mon-
goDB does not guarantee the order of query results.

Ascending/Descending Sort Specify in the sort parameter the field or fields to sort by and a value of 1 or -1 to
specify an ascending or descending sort respectively.
The following sample document specifies a descending sort by the age field and then an ascending sort by the posts
field:
{ age : -1, posts: 1 }

94 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

When comparing values of different BSON types, MongoDB uses the following comparison order, from lowest to
highest:
1. MinKey (internal type)
2. Null
3. Numbers (ints, longs, doubles)
4. Symbol, String
5. Object
6. Array
7. BinData
8. ObjectId
9. Boolean
10. Date
11. Timestamp
12. Regular Expression
13. MaxKey (internal type)
MongoDB treats some types as equivalent for comparison purposes. For instance, numeric types undergo conversion
before comparison.
Changed in version 3.0.0: Date objects sort before Timestamp objects. Previously Date and Timestamp objects sorted
together.
The comparison treats a non-existent field as it would an empty BSON Object. As such, a sort on the a field in
documents { } and { a: null } would treat the documents as equivalent in sort order.
With arrays, a less-than comparison or an ascending sort compares the smallest element of arrays, and a greater-than
comparison or a descending sort compares the largest element of the arrays. As such, when comparing a field whose
value is a single-element array (e.g. [ 1 ]) with non-array fields (e.g. 2), the comparison is between 1 and 2. A
comparison of an empty array (e.g. [ ]) treats the empty array as less than null or a missing field.
MongoDB sorts BinData in the following order:
1. First, the length or size of the data.
2. Then, by the BSON one-byte subtype.
3. Finally, by the data, performing a byte-by-byte comparison.

Metadata Sort Specify in the sort parameter a new field name for the computed metadata and specify the $meta
(page 462) expression as its value.
The following sample document specifies a descending sort by the "textScore" metadata:
{ score: { $meta: "textScore" } }

The specified metadata determines the sort order. For example, the "textScore" metadata sorts in descending
order. See $meta (page 462) for details.

2.1. mongo Shell Methods 95


MongoDB Reference Manual, Release 3.0.7

Restrictions When unable to obtain the sort order from an index, MongoDB will sort the results in memory, which
requires that the result set being sorted is less than 32 megabytes.
When the sort operation consumes more than 32 megabytes, MongoDB returns an error. To avoid this error, either cre-
ate an index supporting the sort operation (see Sort and Index Use (page 96)) or use sort() (page 94) in conjunction
with limit() (page 86) (see Limit Results (page 96)).

Sort and Index Use The sort can sometimes be satisfied by scanning an index in order. If the query plan uses an
index to provide the requested sort order, MongoDB does not perform an in-memory sorting of the result set. For more
information, see [Link]

Limit Results You can use sort() (page 94) in conjunction with limit() (page 86) to return the first (in terms
of the sort order) k documents, where k is the specified limit.
If MongoDB cannot obtain the sort order via an index scan, then MongoDB uses a top-k sort algorithm. This algorithm
buffers the first k results (or last, depending on the sort order) seen so far by the underlying index or collection access.
If at any point the memory footprint of these k results exceeds 32 megabytes, the query will fail.

Interaction with Projection When a set of results are both sorted and projected, the MongoDB query engine will
always apply the sorting first.

Examples A collection orders contain the following documents:


{ _id: 1, item: { category: "cake", type: "chiffon" }, amount: 10 }
{ _id: 2, item: { category: "cookies", type: "chocolate chip" }, amount: 50 }
{ _id: 3, item: { category: "cookies", type: "chocolate chip" }, amount: 15 }
{ _id: 4, item: { category: "cake", type: "lemon" }, amount: 30 }
{ _id: 5, item: { category: "cake", type: "carrot" }, amount: 20 }
{ _id: 6, item: { category: "brownies", type: "blondie" }, amount: 10 }

The following query, which returns all documents from the orders collection, does not specify a sort order:
[Link]()

The query returns the documents in indeterminate order:


{ "_id" : 1, "item" : { "category" : "cake", "type" : "chiffon" }, "amount" : 10 }
{ "_id" : 2, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 50 }
{ "_id" : 3, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 15 }
{ "_id" : 4, "item" : { "category" : "cake", "type" : "lemon" }, "amount" : 30 }
{ "_id" : 5, "item" : { "category" : "cake", "type" : "carrot" }, "amount" : 20 }
{ "_id" : 6, "item" : { "category" : "brownies", "type" : "blondie" }, "amount" : 10 }

The following query specifies a sort on the amount field in descending order.
[Link]().sort( { amount: -1 } )

The query returns the following documents, in descending order of amount:


{ "_id" : 2, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 50 }
{ "_id" : 4, "item" : { "category" : "cake", "type" : "lemon" }, "amount" : 30 }
{ "_id" : 5, "item" : { "category" : "cake", "type" : "carrot" }, "amount" : 20 }
{ "_id" : 3, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 15 }
{ "_id" : 1, "item" : { "category" : "cake", "type" : "chiffon" }, "amount" : 10 }
{ "_id" : 6, "item" : { "category" : "brownies", "type" : "blondie" }, "amount" : 10 }

96 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

The following query specifies the sort order using the fields from an embedded document item. The query sorts first
by the category field in ascending order, and then within each category, by the type field in ascending order.
[Link]().sort( { "[Link]": 1, "[Link]": 1 } )

The query returns the following documents, ordered first by the category field, and within each category, by the
type field:
{ "_id" : 6, "item" : { "category" : "brownies", "type" : "blondie" }, "amount" : 10 }
{ "_id" : 5, "item" : { "category" : "cake", "type" : "carrot" }, "amount" : 20 }
{ "_id" : 1, "item" : { "category" : "cake", "type" : "chiffon" }, "amount" : 10 }
{ "_id" : 4, "item" : { "category" : "cake", "type" : "lemon" }, "amount" : 30 }
{ "_id" : 2, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 50 }
{ "_id" : 3, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 15 }

Return in Natural Order The $natural (page 580) parameter returns items according to their natural order
within the database. This ordering is an internal implementation feature, and you should not rely on any particular
structure within it.

Index Use Queries that include a sort by $natural (page 580) order do not use indexes to fulfill the query
predicate with the following exception: If the query predicate is an equality condition on the _id field { _id:
<value> }, then the query with the sort by $natural (page 580) order can use the _id index.

MMAPv1 Typically, the natural order reflects insertion order with the following exception for the MMAPv1 storage
engine. For the MMAPv1 storage engine, the natural order does not reflect insertion order if the documents relocate
because of document growth or remove operations free up space which are then taken up by newly inserted documents.
Consider to following example which uses the MMAPv1 storage engine.
The following sequence of operations inserts documents into the trees collection:
[Link]( { _id: 1, common_name: "oak", genus: "quercus" } )
[Link]( { _id: 2, common_name: "chestnut", genus: "castanea" } )
[Link]( { _id: 3, common_name: "maple", genus: "aceraceae" } )
[Link]( { _id: 4, common_name: "birch", genus: "betula" } )

The following query returns the documents in the natural order:


[Link]().sort( { $natural: 1 } )

The documents return in the following order:


{ "_id" : 1, "common_name" : "oak", "genus" : "quercus" }
{ "_id" : 2, "common_name" : "chestnut", "genus" : "castanea" }
{ "_id" : 3, "common_name" : "maple", "genus" : "aceraceae" }
{ "_id" : 4, "common_name" : "birch", "genus" : "betula" }

Update a document such that the document outgrows its current allotted space:
[Link](
{ _id: 1 },
{ $set: { famous_oaks: [ "Emancipation Oak", "Goethe Oak" ] } }
)

Rerun the query to returns the documents in natural order:

2.1. mongo Shell Methods 97


MongoDB Reference Manual, Release 3.0.7

[Link]().sort( { $natural: 1 } )

For MongoDB instances using MMAPv1, the documents return in the following natural order, which no longer reflects
the insertion order:
{ "_id" : 2, "common_name" : "chestnut", "genus" : "castanea" }
{ "_id" : 3, "common_name" : "maple", "genus" : "aceraceae" }
{ "_id" : 4, "common_name" : "birch", "genus" : "betula" }
{ "_id" : 1, "common_name" : "oak", "genus" : "quercus", "famous_oaks" : [ "Emancipation Oak", "Goeth

See also:
$natural (page 580)

[Link]()

[Link]()
The toArray() (page 98) method returns an array that contains all the documents from a cursor. The method
iterates completely the cursor, loading all the documents into RAM and exhausting the cursor.
Returns An array of documents.
Consider the following example that applies toArray() (page 98) to the cursor returned from the find() (page 35)
method:
var allProductsArray = [Link]().toArray();

if ([Link] > 0) { printjson (allProductsArray[0]); }

The variable allProductsArray holds the array of documents returned by toArray() (page 98).

2.1.3 Database

Database Methods

Name Description
[Link]() (page 99) Copies data directly between MongoDB instances. Wraps cloneCollec
[Link]() (page 100) Copies a database from a remote host to the current host. Wraps clone (p
[Link]() (page 100) Returns help information for a database command.
[Link]() (page 100) Copies a database to another database on the current host. Wraps copydb
[Link]() (page 103) Creates a new collection. Commonly used to create a capped collection.
[Link]() (page 105) Reports the current in-progress operations.
[Link]() (page 111) Removes the current database.
[Link]() (page 112) Deprecated. Passes a JavaScript function to the mongod (page 603) instan
[Link]() (page 114) Flushes writes to disk and locks the database to prevent write operations an
[Link]() (page 114) Allows writes to continue on a database locked with [Link]() (
[Link]() (page 115) Returns a collection object. Used to access collections with names that are
[Link]() (page 115) Returns collection information for all collections in the current database.
[Link]() (page 116) Lists all collections in the current database.
[Link]() (page 116) Checks and returns the status of the last operation. Wraps getLastErro
[Link]() (page 117) Returns the status document for the last operation. Wraps getLastErro
[Link]() (page 117) Returns the log message verbosity levels.
[Link]() (page 119) Returns the Mongo() (page 212) connection object for the current connec

98 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Table 2.2 continued from previous page


Name Description
[Link]() (page 119) Returns the name of the current database.
[Link]() (page 119) Returns a status document containing all errors since the last error reset. W
[Link]() (page 119) Returns the current profiling level for database operations.
[Link]() (page 119) Returns a document that reflects the current profiling level and the profiling
[Link]() (page 119) Returns a document with replication statistics.
[Link]() (page 120) Provides access to the specified database.
[Link]() (page 121) Displays descriptions of common db object methods.
[Link]() (page 121) Returns a document with information about the system MongoDB runs on.
[Link]() (page 122) Returns a document that reports the state of the replica set.
[Link]() (page 122) Terminates a specified operation.
[Link]() (page 122) Displays a list of common database commands.
[Link]() (page 122) Loads all scripts in the [Link] collection for the current database int
[Link]() (page 123) Ends an authenticated session.
[Link]() (page 123) Prints statistics from every collection. Wraps [Link](
[Link]() (page 123) Prints a report of the status of the replica set from the perspective of the pri
[Link]() (page 124) Prints a report of the sharding configuration and the chunk ranges.
[Link]() (page 125) Prints a report of the status of the replica set from the perspective of the sec
[Link]() (page 125) Runs a repair routine on the current database.
[Link]() (page 126) Resets the error message returned by [Link]() (page 119)
[Link]() (page 126) Runs a database command (page 219).
[Link]() (page 126) Returns a document that displays the compilation parameters for the mong
[Link]() (page 126) Returns a document with information about the runtime used to start the M
[Link]() (page 126) Returns a document that provides an overview of the state of the database p
[Link]() (page 127) Sets a single log message verbosity level.
[Link]() (page 128) Modifies the current level of database profiling.
[Link]() (page 129) Shuts down the current mongod (page 603) or mongos (page 622) proces
[Link]() (page 129) Returns a document that reports on the state of the current database.
[Link]() (page 129) Returns the version of the mongod (page 603) instance.
[Link]() (page 129) Performs a preliminary check for upgrade preparedness for a specific datab
[Link]() (page 131) Performs a preliminary check for upgrade preparedness for all databases an

[Link]()

Definition
[Link](from, collection, query)
Copies data directly between MongoDB instances. The [Link]() (page 99) method wraps
the cloneCollection (page 344) database command and accepts the following arguments:
param string from The address of the server to clone from.
param string collection The collection in the MongoDB instance that you want to copy.
[Link]() (page 99) will only copy the collection with this name from
database of the same name as the current database the remote MongoDB instance.
If you want to copy a collection from a different database name you must use the
cloneCollection (page 344) directly.
param document query Optional. A standard query document that limits the documents copied as
part of the [Link]() (page 99) operation. All query selectors (page 413)
available to the find() (page 35) are available here.

Behavior mongos (page 622) does not support [Link]() (page 99).

2.1. mongo Shell Methods 99


MongoDB Reference Manual, Release 3.0.7

Changed in version 3.0: If the given namespace already exists in the destination mongod (page 603) instance,
[Link]() (page 99) will return an error.

[Link]()

Definition
[Link](hostname)
Copies a remote database to the current database. The command assumes that the remote database has the same
name as the current database.
param string hostname The hostname of the database to copy.
This method provides a wrapper around the MongoDB database command clone (page 344). The copydb
(page 335) database command provides related functionality.

Example To clone a database named importdb on a host named hostname, issue the following:
use importdb
[Link]("hostname")

New databases are implicitly created, so the current host does not need to have a database named importdb for this
command to succeed.

[Link]()

Description
[Link](command)
Displays help text for the specified database command. See the Database Commands (page 219).
The [Link]() (page 100) method has the following parameter:
param string command The name of a database command.

[Link]()

Definition
[Link](fromdb, todb, fromhost, username, password, mechanism)
Changed in version 3.0: When authenticating to the fromhost instance, [Link]() (page 100)
supports MONGODB-CR and SCRAM-SHA-1 mechanisms to authenticate the fromhost user.
Copies a database either from one mongod (page 603) instance to the current mongod (page 603) instance or
within the current mongod (page 603). [Link]() (page 100) wraps the copydb (page 335)
command and takes the following arguments:
param string fromdb Name of the source database.
param string todb Name of the target database.
param string fromhost Optional. The hostname of the source mongod (page 603) instance. Omit
to copy databases within the same mongod (page 603) instance.
param string username Optional. The name of the user on the fromhost MongoDB instance.
The user authenticates to the fromdb.
For more information, see Authentication to Source mongod Instance (page 101).

100 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

param string password Optional. The password on the fromhost for authentication. The method
does not transmit the password in plaintext.
For more information, see Authentication to Source mongod Instance (page 101).
param string mechanism Optional. The mechanism to authenticate the username and
password on the fromhost. Specify either MONGODB-CR or SCRAM-SHA-1.
[Link] (page 100) defaults to SCRAM-SHA-1 if the wire protocol version
(maxWireVersion (page 310)) is greater than or equal to 3 (i.e. MongoDB versions 3.0
or greater). Otherwise, it defaults to MONGODB-CR.
Specify MONGODB-CR to authenticate to the version 2.6.x fromhost from a version 3.0 in-
stance or greater. For an example, see Copy Database from a mongod Instances that Enforce
Authentication (page 103).
New in version 3.0.

Behavior

Destination
Run [Link]() (page 100) in the admin database of the destination mongod (page 603) in-
stance, i.e. the instance receiving the copied data.
[Link]() (page 100) creates the target database if it does not exist.
[Link]() (page 100) requires enough free disk space on the host instance for the copied
database. Use the [Link]() (page 129) operation to check the size of the database on the source mongod
(page 603) instance.

Authentication to Source mongod Instance


If copying from another mongod (page 603) instance (fromhost) that enforces access control
(page 736), then you must authenticate to the fromhost instance by specifying the username, password,
and optionally mechanism. The method does not transmit the password in plaintext.
When authenticating to the fromhost instance, [Link]() (page 100) uses the fromdb as the
authentication database for the specified user.
When authenticating to the fromhost instance, [Link]() (page 100) supports MONGODB-
CR and SCRAM-SHA-1 mechanisms to authenticate the fromhost user.
To authenticate to a version 2.6 fromhost, you must specify MONGODB-CR as the authentication mech-
anism. See Copy Database from a mongod Instances that Enforce Authentication (page 103).
To copy from a version 3.0 fromhost to a version 2.6 instance, i.e. if running the method from a version
2.6 instance to copy from a version 3.0 fromhost, you can only authenticate to the fromhost as a
MONGODB-CR user.
For more information on required access and authentication, see Required Access (page 102).

Concurrency
[Link]() (page 100) and clone (page 344) do not produce point-in-time snapshots of the
source database. Write traffic to the source or destination database during the copy process will result in diver-
gent data sets.

2.1. mongo Shell Methods 101


MongoDB Reference Manual, Release 3.0.7

[Link]() (page 100) does not lock the destination server during its operation, so the copy will
occasionally yield to allow other operations to complete.

Sharded Clusters
Do not use [Link]() (page 100) from a mongos (page 622) instance.
Do not use [Link]() (page 100) to copy databases that contain sharded collections.

Required Access Changed in version 2.6.

Source Database (fromdb) If the mongod (page 603) instance of the source database (fromdb) enforces
access control (page 736), you must have proper authorization for the source database.
If copying from another mongod (page 603) instance (fromhost) that enforces access control (page 736),
then you must authenticate to the fromhost instance by specifying the username, password, and optionally
mechanism. The method does not transmit the password in plaintext.
When authenticating to the fromhost instance, [Link]() (page 100) uses the fromdb as the au-
thentication database for the specified user.
When authenticating to the fromhost instance, [Link]() (page 100) supports MONGODB-CR and
SCRAM-SHA-1 mechanisms to authenticate the fromhost user.
To authenticate to a version 2.6 fromhost, you must specify MONGODB-CR as the authentication mechanism.
See Copy Database from a mongod Instances that Enforce Authentication (page 103).
To copy from a version 3.0 fromhost to a version 2.6 instance, i.e. if running the method from a version 2.6
instance to copy from a version 3.0 fromhost, you can only authenticate to the fromhost as a MONGODB-CR
user.

Source is non-admin Database Changed in version 3.0.


If the source database is a non-admin database, you must have privileges that specify find, listCollections,
and listIndexes actions on the source database, and find action on the [Link] collection in the source
database.
{ resource: { db: "mySourceDB", collection: "" }, actions: [ "find", "listCollections", "listIndexes"
{ resource: { db: "mySourceDB", collection: "[Link]" }, actions: [ "find" ] },

Source is admin Database Changed in version 3.0.


If the source database is the admin database, you must have privileges that specify find, listCollections,
and listIndexes actions on the admin database, and find action on the [Link], [Link],
[Link], and [Link] collections in the admin database. For example:
{ resource: { db: "admin", collection: "" }, actions: [ "find", "listCollections", "listIndexes" ] }
{ resource: { db: "admin", collection: "[Link]" }, actions: [ "find" ] },
{ resource: { db: "admin", collection: "[Link]" }, actions: [ "find" ] },
{ resource: { db: "admin", collection: "[Link]" }, actions: [ "find" ] },
{ resource: { db: "admin", collection: "[Link]" }, actions: [ "find" ] }

Target Database (todb) If the mongod (page 603) instance of the target database (todb) enforces access
control (page 736), you must have proper authorization for the target database.

102 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Copy from non-admin Database If the source database is not the admin database, you must have privileges
that specify insert and createIndex actions on the target database, and insert action on the [Link]
collection in the target database. For example:
{ resource: { db: "myTargetDB", collection: "" }, actions: [ "insert", "createIndex" ] },
{ resource: { db: "myTargetDB", collection: "[Link]" }, actions: [ "insert" ] }

Copy from admin Database If the source database is the admin database, you must have privileges that
specify insert and createIndex actions on the target database, and insert action on the [Link],
[Link], [Link], and [Link] collections in the target database. For example:
{ resource: { db: "myTargetDB", collection: "" }, actions: [ "insert", "createIndex" ] },
{ resource: { db: "myTargetDB", collection: "[Link]" }, actions: [ "insert" ] },
{ resource: { db: "myTargetDB", collection: "[Link]" }, actions: [ "insert" ] },
{ resource: { db: "myTargetDB", collection: "[Link]" }, actions: [ "insert" ] },
{ resource: { db: "myTargetDB", collection: "[Link]" }, actions: [ "insert" ] }

Example

Copy from the Same mongod Instance To copy within the same mongod (page 603) instance, omit the
fromhost.
The following operation copies a database named records into a database named archive_records:
[Link]('records', 'archive_records')

Copy Database from a mongod Instances that Enforce Authentication If copying from another mongod
(page 603) instance (fromhost) that enforces access control (page 736), then you must authenticate to the
fromhost instance by specifying the username, password, and optionally mechanism. The method does not
transmit the password in plaintext.
When authenticating to the fromhost instance, [Link]() (page 100) uses the fromdb as the au-
thentication database for the specified user.
Changed in version 3.0: MongoDB 3.0 supports passing the authentication mechanism to use for the fromhost.
The following operation copies a database named reporting from a version 2.6 mongod (page 603) instance that
runs on [Link] and enforces access control.
[Link](
"reporting",
"reporting_copy",
"[Link]",
"reportUser",
"abc123",
"MONGODB-CR"
)

See also:
clone (page 344)

[Link]()

Definition

2.1. mongo Shell Methods 103


MongoDB Reference Manual, Release 3.0.7

[Link](name, options)
Creates a new collection explicitly.
Because MongoDB creates a collection implicitly when the collection is first referenced in a command, this
method is used primarily for creating new capped collections. This is also used to pre-allocate space for an
ordinary collection.
The [Link]() (page 103) method has the following prototype form:
[Link](<name>, { capped: <boolean>,
autoIndexId: <boolean>,
size: <number>,
max: <number>,
storageEngine: <document> } )

The [Link]() (page 103) method has the following parameters:


param string name The name of the collection to create.
param document options Optional. Configuration options for creating a capped collection or for
preallocating space in a new collection.
The options document creates a capped collection or preallocates space in a new ordinary collection. The
options document contains the following fields:
field boolean capped Optional. To create a capped collection, specify true. If you specify true,
you must also set a maximum size in the size field.
field boolean autoIndexId Optional. Specify false to disable the automatic creation of an index
on the _id field.

Important: For replica sets, all collections must have autoIndexId set to true.

field number size Optional. Specify a maximum size in bytes for a capped collection. Once a
capped collection reaches its maximum size, MongoDB removes the older documents to make
space for the new documents. The size field is required for capped collections and ignored for
other collections.
field number max Optional. The maximum number of documents allowed in the capped collection.
The size limit takes precedence over this limit. If a capped collection reaches the size limit
before it reaches the maximum number of documents, MongoDB removes old documents. If
you prefer to use the max limit, ensure that the size limit, which is required for a capped
collection, is sufficient to contain the maximum number of documents.
field boolean usePowerOf2Sizes Optional. Available for the MMAPv1 storage engine only.
Deprecated since version 3.0: For the MMAPv1 storage engine, all collections use the power of
2 sizes allocation unless the noPadding option is true. The usePowerOf2Sizes option
does not affect the allocation strategy.
field boolean noPadding Optional. Available for the MMAPv1 storage engine only.
New in version 3.0: noPadding flag disables the power of 2 sizes allocation for the collection.
With noPadding flag set to true, the allocation strategy does not include additional space to
accommodate document growth, as such, document growth will result in new allocation. Use
for collections with workloads that are insert-only or in-place updates (such as incrementing
counters).
Defaults to false.

104 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Warning: Do not set noPadding if the workload includes removes or any updates that
may cause documents to grow. For more information, see exact-fit-allocation.

field document storageEngine Optional. Available for the WiredTiger storage engine only.
New in version 3.0.
Allows users to specify configuration to the storage engine on a per-collection basis when creat-
ing a collection. The value of the storageEngine option should take the following form:

{ <storage-engine-name>: <options> }

Storage engine configuration specified when creating collections are validated and logged to the
oplog during replication to support replica sets with members that use different storage engines.

Examples

Create a Capped Collection Capped collections have maximum size or document counts that prevent them from
growing beyond maximum thresholds. All capped collections must specify a maximum size and may also specify
a maximum document count. MongoDB removes older documents if a collection reaches the maximum size limit
before it reaches the maximum document count. Consider the following example:
[Link]("log", { capped : true, size : 5242880, max : 5000 } )

This command creates a collection named log with a maximum size of 5 megabytes and a maximum of 5000 docu-
ments.
The following command simply pre-allocates a 2-gigabyte, uncapped collection named people:
[Link]("people", { size: 2147483648 } )

This command provides a wrapper around the database command create (page 342). See
[Link] for more information about
capped collections.

Specify Storage Engine Options New in version 3.0.


You can specify collection-specific storage engine configuration options when you create a collection with
[Link]() (page 103). Consider the following operation:
[Link](
"users",
{ storageEngine: { wiredTiger: { configString: "<option>=<setting>" } } }
)

This operation creates a new collection named users with a specific configuration string that MongoDB will pass
to the wiredTiger storage engine. See the WiredTiger documentation of collection level options6 for specific
wiredTiger options.

[Link]()

Definition
6 [Link]

2.1. mongo Shell Methods 105


MongoDB Reference Manual, Release 3.0.7

[Link]()
Returns a document that contains information on in-progress operations for the database instance.
[Link]() (page 105) method has the following form:
[Link](<operations>)

The [Link]() (page 105) method can take the following optional argument:
param boolean or document operations Optional. Specifies the operations to report on. Can pass
either a boolean or a document.
Specify true to include operations on idle connections and system operations. Specify a docu-
ment with query conditions to report only on operations that match the conditions. See Behavior
(page 106) for details.

Behavior If you pass in true to [Link]() (page 105), the method returns information on all operations,
including operations on idle connections and system operations.
[Link](true)

Passing in true is equivalent to passing in a query document of { $all: true }.


If you pass a query document to [Link]() (page 105), the output returns information only for the current
operations that match the query. You can query on the Output Fields (page 108). See Examples (page 106).
You can also specify { $all: true } query document to return information on all in-progress operations,
including operations on idle connections and system operations. If the query document includes $all: true
as well as other query conditions, only the $all: true applies.

Access Control On systems running with authorization (page 736), a user must have access that includes the
inprog action. For example, see create-role-to-manage-ops.

Examples The following examples use the [Link]() (page 105) method with various query documents
to filter the output.

Write Operations Waiting for a Lock The following example returns information on all write operations that are
waiting for a lock:
[Link](
{
"waitingForLock" : true,
$or: [
{ "op" : { "$in" : [ "insert", "update", "remove" ] } },
{ "[Link]": { $exists: true } }
]
}
)

Active Operations with no Yields The following example returns information on all active running operations that
have never yielded:
[Link](
{
"active" : true,
"numYields" : 0,

106 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

"waitingForLock" : false
}
)

Active Operations on a Specific Database The following example returns information on all active operations for
database db1 that have been running longer than 3 seconds:
[Link](
{
"active" : true,
"secs_running" : { "$gt" : 3 },
"ns" : /^db1\./
}
)

Active Indexing Operations The following example returns information on index creation operations:
[Link](
{
$or: [
{ op: "query", "[Link]": { $exists: true } },
{ op: "insert", ns: /\.system\.indexes\b/ }
]
}
)

Output Example The following is an prototype of [Link]() (page 105) output.


{
"inprog": [
{
"desc" : <string>,
"threadId" : <string>,
"connectionId" : <number>,
"opid" : <number>,
"active" : <boolean>,
"secs_running" : <NumberLong()>,
"microsecs_running" : <number>,
"op" : <string>,
"ns" : <string>,
"query" : <document>,
"insert" : <document>,
"planSummary": <string>,
"client" : <string>,
"msg": <string>,
"progress" : {
"done" : <number>,
"total" : <number>
},
"killPending" : <boolean>,
"numYields" : <number>,
"locks" : {
"Global" : <string>,
"MMAPV1Journal" : <string>,
"Database" : <string>,

2.1. mongo Shell Methods 107


MongoDB Reference Manual, Release 3.0.7

"Collection" : <string>,
"Metadata" : <string>,
"oplog" : <string>
},
"waitingForLock" : <boolean>,
"lockStats" : {
"Global": {
"acquireCount": {
"r": <NumberLong>,
"w": <NumberLong>,
"R": <NumberLong>,
"W": <NumberLong>
},
"acquireWaitCount": {
"r": <NumberLong>,
"w": <NumberLong>,
"R": <NumberLong>,
"W": <NumberLong>
},
"timeAcquiringMicros" : {
"r" : NumberLong(0),
"w" : NumberLong(0),
"R" : NumberLong(0),
"W" : NumberLong(0)
},
"deadlockCount" : {
"r" : NumberLong(0),
"w" : NumberLong(0),
"R" : NumberLong(0),
"W" : NumberLong(0)
}
},
"MMAPV1Journal": {
...
},
"Database" : {
...
},
...
}
},
...
],
"fsyncLock": <boolean>,
"info": <string>
}

Output Fields
[Link]
A description of the client. This string includes the connectionId (page 108).
[Link]
An identifier for the thread that handles the operation and its connection.
[Link]
An identifier for the connection where the operation originated.
[Link]

108 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

The identifier for the operation. You can pass this value to [Link]() (page 122) in the mongo (page 632)
shell to terminate the operation.

Warning: Terminate running operations with extreme caution. Only use [Link]() (page 122) to
terminate operations initiated by clients and do not terminate internal database operations.

[Link]
A boolean value specifying whether the operation has started. Value is true if the operation has started or
false if the operation is idle, such as an idle connection or an internal thread that is currently idle. An
operation can be active even if the operation has yielded to another operation.
Changed in version 3.0: For some inactive background threads, such as an inactive
signalProcessingThread, MongoDB suppresses various empty fields.
currentOp.secs_running
The duration of the operation in seconds. MongoDB calculates this value by subtracting the current time from
the start time of the operation.
Only appears if the operation is running; i.e. if active (page 109) is true.
currentOp.microsecs_running
New in version 2.6.
The duration of the operation in microseconds. MongoDB calculates this value by subtracting the current time
from the start time of the operation.
Only appears if the operation is running; i.e. if active (page 109) is true.
[Link]
A string that identifies the type of operation. The possible values are:
"none"
"update"
"insert"
"query"
"getmore"
"remove"
"killcursors"
"query" operations include read operations as well as most commands such as the createIndexes
(page 347) command and the findandmodify command.
Changed in version 3.0: Write operations that use the insert (page 244), update (page 246), and delete
(page 251) commands respectively display "insert", "update", and "delete" for op (page 109). Pre-
vious versions include these write commands under "query" operations.
[Link]
The namespace the operation targets. A namespace consists of the database name and the collection name
concatenated with a dot (.); that is, "<database>.<collection>".
[Link]
Contains the document to be inserted for operations with op (page 109) value of "insert". Only appears for
operations with op (page 109) value "insert".
Insert operations such as [Link]() (page 52) that use the insert (page 244) command
will have op (page 109) value of "query".

2.1. mongo Shell Methods 109


MongoDB Reference Manual, Release 3.0.7

[Link]
A document containing information on operations whose op (page 109) value is not "insert". For instance,
for a [Link]() (page 35) operation, the query (page 109) contains the query predicate.
query (page 109) does not appear for op (page 109) of "insert". query (page 109) can also be an empty
document.
For "update" (page 109) or "remove" (page 109) operations or for read operations categorized under
"query" (page 109), the query (page 109) document contains the query predicate for the operations.
Changed in version 3.0.4: For "getmore" (page 109) operations on cursors returned from a
[Link]() (page 35) or a [Link]() (page 20), the query
(page 109) field contains respectively the query predicate or the issued aggregate (page 219) command
document. For details on the aggregate (page 219) command document, see the aggregate (page 219)
reference page.
For other commands categorized under "query" (page 109), query (page 109) contains the issued command
document. Refer to the specific command reference page for the details on the command document.
Changed in version 3.0: Previous versions categorized operations that used write commands under op
(page 109) of "query" and returned the write command information (e.g. query predicate, update statement,
and update options) in query (page 109) document.
[Link]
A string that contains the query plan to help debug slow queries.
[Link]
The IP address (or hostname) and the ephemeral port of the client connection where the operation originates. If
your inprog array has operations from many different clients, use this string to relate operations to clients.
[Link]
Changed in version 3.0.
The locks (page 110) document reports the type and mode of locks the operation currently holds. The possible
lock types are as follows:
Global represents global lock.
MMAPV1Journal represents MMAPv1 storage engine specific lock to synchronize journal writes; for
non-MMAPv1 storage engines, the mode for MMAPV1Journal is empty.
Database represents database lock.
Collection represents collection lock.
Metadata represents metadata lock.
oplog represents lock on the oplog.
The possible modes are as follows:
R represents Shared (S) lock.
W represents Exclusive (X) lock.
r represents Intent Shared (IS) lock.
w represents Intent Exclusive (IX) lock.
[Link]
Returns a boolean value. waitingForLock (page 110) is true if the operation is waiting for a lock and
false if the operation has the required lock.

110 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link]
The msg (page 110) provides a message that describes the status and progress of the operation. In the case of
indexing or mapReduce operations, the field reports the completion percentage.
[Link]
Reports on the progress of mapReduce or indexing operations. The progress (page 111) fields corresponds
to the completion percentage in the msg (page 110) field. The progress (page 111) specifies the following
information:
[Link]
Reports the number completed.
[Link]
Reports the total number.
[Link]
Returns true if the operation is currently flagged for termination. When the operation encounters its next safe
termination point, the operation will terminate.
[Link]
numYields (page 111) is a counter that reports the number of times the operation has yielded to allow other
operations to complete.
Typically, operations yield when they need access to data that MongoDB has not yet fully read into memory.
This allows other operations that have data in memory to complete quickly while MongoDB reads in data for
the yielding operation.
[Link]
Specifies if database is currently locked for fsync write/snapshot (page 114).
Only appears if locked; i.e. if fsyncLock (page 111) is true.
[Link]
Information regarding how to unlock database from [Link]() (page 114). Only appears if
fsyncLock (page 111) is true.
[Link]
For each lock type and mode (see [Link] (page 110) for descriptions of lock types and modes),
returns the following information:
[Link]
Number of times the operation acquired the lock in the specified mode.
[Link]
Number of times the operation had to wait for the acquireCount (page 111) lock acquisitions because
the locks were held in a conflicting mode. acquireWaitCount (page 111) is less than or equal to
acquireCount (page 111).
[Link]
Cumulative time in microseconds that the operation had to wait to acquire the locks.
timeAcquiringMicros (page 111) divided by acquireWaitCount (page 111) gives an approxi-
mate average wait time for the particular lock mode.
[Link]
Number of times the operation encountered deadlocks while waiting for lock acquisitions.

[Link]()

Definition

2.1. mongo Shell Methods 111


MongoDB Reference Manual, Release 3.0.7

[Link]()
Removes the current database, deleting the associated data files.

Behavior The [Link]() (page 111) wraps the dropDatabase (page 340) command.

Warning: This command obtains a global write lock and will block other operations until it has completed.

Changed in version 2.6: This command does not delete the users associated with the current database. To drop the
associated users, run the dropAllUsersFromDatabase (page 281) command in the database you are deleting.

Example The following example in the mongo (page 632) shell uses the use <database> operation to switch
the current database to the temp database and then uses the [Link]() (page 111) method to drops the
temp database:
use temp
[Link]()

See also:
dropDatabase (page 340)

[Link]()

Definition
[Link](function, arguments)
Deprecated since version 3.0.
Provides the ability to run JavaScript code on the MongoDB server.
The helper [Link]() (page 112) in the mongo (page 632) shell wraps the eval (page 262) command.
Therefore, the helper method shares the characteristics and behavior of the underlying command with one ex-
ception: [Link]() (page 112) method does not support the nolock option.
The method accepts the following parameters:
param function function A JavaScript function to execute.
param list arguments Optional. A list of arguments to pass to the JavaScript function. Omit if the
function does not take arguments.
The JavaScript function need not take any arguments, as in the first example, or may optionally take arguments
as in the second:
function () {
// ...
}

function (arg1, arg2) {


// ...
}

Behavior

112 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Write Lock By default, [Link]() (page 112) takes a global write lock while evaluating the JavaScript function.
As a result, [Link]() (page 112) blocks all other read and write operations to the database while the [Link]()
(page 112) operation runs.
To prevent the taking of the global write lock while evaluating the JavaScript code, use the eval (page 262) command
with nolock set to true. nolock does not impact whether the operations within the JavaScript code take write
locks.
For long running [Link]() (page 112) operation, consider using either the eval command with nolock: true
or using other server side code execution options.

Sharded Data You can not use [Link]() (page 112) with sharded collections. In general, you should avoid
using [Link]() (page 112) in sharded clusters; nevertheless, it is possible to use [Link]() (page 112) with
non-sharded collections and databases stored in a sharded cluster.

Access Control Changed in version 2.6.


If authorization is enabled, you must have access to all actions on all resources in order to run eval (page 262).
Providing such access is not recommended, but if your organization requires a user to run eval (page 262), create a
role that grants anyAction on resource-anyresource. Do not assign this role to any other user.

JavaScript Engine Changed in version 2.4.


The V8 JavaScript engine, which became the default in 2.4, allows multiple JavaScript operations to execute at the
same time. Prior to 2.4, [Link]() (page 112) executed in a single thread.

Examples The following is an example of the [Link]() (page 112) method:


[Link]( function(name, incAmount) {
var doc = [Link]( { name : name } );

doc = doc || { name : name , num : 0 , total : 0 , avg : 0 };

[Link]++;
[Link] += incAmount;
[Link] = [Link] / [Link];

[Link]( doc );
return doc;
},
"eliot", 5 );

The db in the function refers to the current database.


"eliot" is the argument passed to the function, and corresponds to the name argument.
5 is an argument to the function and corresponds to the incAmount field.
If you want to use the servers interpreter, you must run [Link]() (page 112). Otherwise, the mongo (page 632)
shells JavaScript interpreter evaluates functions entered directly into the shell.
If an error occurs, [Link]() (page 112) throws an exception. The following is an example of an invalid function
that uses the variable x without declaring it as an argument:
[Link]( function() { return x + x; }, 3 );

The statement results in the following exception:

2.1. mongo Shell Methods 113


MongoDB Reference Manual, Release 3.0.7

{
"errmsg" : "exception: JavaScript execution failed: ReferenceError: x is not defined near '{ retur
"code" : 16722,
"ok" : 0
}

See also:
[Link]

[Link]()

Definition
[Link]()
Forces the mongod (page 603) to flush all pending write operations to the disk and locks the entire mongod
(page 603) instance to prevent additional writes until the user releases the lock with the [Link]()
(page 114) command. [Link]() (page 114) is an administrative command.
This command provides a simple wrapper around a fsync (page 351) database command with the following
syntax:
{ fsync: 1, lock: true }

This function locks the database and create a window for backup operations.

Behavior

Compatibility with WiredTiger New in version 3.0.


With WiredTiger, the [Link]() (page 114) and [Link]() (page 114) operations cannot guar-
antee that the data files do not change. As a result, do not use these methods to ensure consistency for the purposes of
creating backups.

Impact on Read Operations [Link]() (page 114) may block reads, including those necessary to ver-
ify authentication. Such reads are necessary to establish new connections to a mongod (page 603) that enforces
authorization checks.

Connection When calling [Link]() (page 114), ensure that the connection is kept open to allow a sub-
sequent call to [Link]() (page 114).
Closing the connection may make it difficult to release the lock.

[Link]()

Definition
[Link]()
Unlocks a mongod (page 603) instance to allow writes and reverses the operation of a [Link]()
(page 114) operation. Typically you will use [Link]() (page 114) following a database backup
operation.
[Link]() (page 114) is an administrative operation.

114 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Wired Tiger Compatibility With WiredTiger, the [Link]() (page 114) and [Link]()
(page 114) operations cannot guarantee that the data files do not change. As a result, do not use these methods to
ensure consistency for the purposes of creating backups.

[Link]()

Description
[Link](name)
Returns a collection name. This is useful for a collection whose name might interact with the shell itself, such
names that begin with _ or that mirror the database commands (page 219).
The [Link]() (page 115) method has the following parameter:
param string name The name of the collection.

[Link]()

Definition
[Link]()
New in version 3.0.0.
Returns an array of documents with collection information, i.e. collection name and options, for the current
database.
The [Link]() (page 115) helper wraps the listCollections (page 340) com-
mand.

Example The following returns information for all collections in the records database:
use records
[Link]()

The method returns an array of documents that contain collection information:


[
{
"name" : "employees",
"options" : {
"flags" : 1
}
},
{
"name" : "products",
"options" : {
"flags" : 1
}
},
{
"name" : "mylogs",
"options" : {
"capped" : true,
"size" : 256
}
},
{
"name" : "[Link]",

2.1. mongo Shell Methods 115


MongoDB Reference Manual, Release 3.0.7

"options" : {
}
}
]

[Link]()

Definition
[Link]()
Returns an array containing the names of all collections in the current database.

Considerations Changed in version 3.0.0.


For MongoDB 3.0 deployments using the WiredTiger storage engine, if you run [Link]()
(page 116) from a version of the mongo (page 632) shell before 3.0 or a version of the driver prior to 3.0 compat-
ible version (page 829), [Link]() (page 116) will return no data, even if there are existing
collections. For more information, see WiredTiger and Driver Version Compatibility (page 825).

Example The following returns the names of all collections in the records database:
use records
[Link]()

The method returns the names of the collections in an array:


[ "employees", "products", "mylogs", "[Link]" ]

[Link]()

Definition
[Link](<w>, <wtimeout>)
Specifies the level of write concern for confirming the success of previous write operation issued over the same
connection and returns the error string (page 260) for that operation.
When using [Link]() (page 116), clients must issue the [Link]() (page 116)
on the same connection as the write operation they wish to confirm.
Changed in version 2.6: A new protocol for write operations (page 876) integrates write concerns with the
write operations, eliminating the need for a separate [Link]() (page 116). Most write methods
(page 882) now return the status of the write operation, including error information. In previous versions, clients
typically used the [Link]() (page 116) in combination with a write operation to verify that the
write succeeded.
The [Link]() (page 116) can accept the following parameters:
param int, string w Optional. The write concerns w value.
param int wtimeout Optional. The time limit in milliseconds.

Behavior The returned error string (page 260) provides error information on the previous write operation.
If the [Link]() (page 116) method itself encounters an error, such as an incorrect write concern value,
the [Link]() (page 116) throws an exception.

116 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Example The following example issues a [Link]() (page 116) operation that verifies that the pre-
ceding write operation, issued over the same connection, has propagated to at least two members of the replica set.
[Link](2)

See also:
getLastError (page 259) and [Link]
for all options, Write Concern for a conceptual overview, [Link]
for information about all write operations in MongoDB.

[Link]()

Definition
[Link]()
Specifies the level of write concern for confirming the success of previous write operation issued over the same
connection and returns the document (page 260) for that operation.
When using [Link]() (page 117), clients must issue the [Link]()
(page 117) on the same connection as the write operation they wish to confirm.
The [Link]() (page 117) is a mongo (page 632) shell wrapper around the
getLastError (page 259) command.
Changed in version 2.6: A new protocol for write operations (page 876) integrates write concerns with the write
operations, eliminating the need for a separate [Link]() (page 117). Most write methods
(page 882) now return the status of the write operation, including error information. In previous versions, clients
typically used the [Link]() (page 117) in combination with a write operation to verify that
the write succeeded.
The [Link]() (page 117) can accept the following parameters:
param int, string key Optional. The write concerns w value.
param int wtimeout Optional. The time limit in milliseconds.

Behavior The returned document (page 260) provides error information on the previous write operation.
If the [Link]() (page 117) method itself encounters an error, such as an incorrect write concern
value, the [Link]() (page 117) throws an exception.
For information on the returned document, see getLastError command (page 260).

Example The following example issues a [Link]() (page 117) operation that verifies that the
preceding write operation, issued over the same connection, has propagated to at least two members of the replica set.
[Link](2)

See also:
Write Concern, [Link] and replica-
set-write-concern.

[Link]()

Definition

2.1. mongo Shell Methods 117


MongoDB Reference Manual, Release 3.0.7

[Link]()
New in version 3.0.
Returns the current verbosity settings. The verbosity settings determine the amount of Log Messages (page 782)
that MongoDB produces for each log message component (page 783).
If a component inherits the verbosity level of its parent, [Link]() (page 117) displays -1
for the components verbosity.

Output The [Link]() (page 117) returns a document with the verbosity settings. For example:
{
"verbosity" : 0,
"accessControl" : {
"verbosity" : -1
},
"command" : {
"verbosity" : -1
},
"control" : {
"verbosity" : -1
},
"geo" : {
"verbosity" : -1
},
"index" : {
"verbosity" : -1
},
"network" : {
"verbosity" : -1
},
"query" : {
"verbosity" : 2
},
"replication" : {
"verbosity" : -1
},
"sharding" : {
"verbosity" : -1
},
"storage" : {
"verbosity" : 2,
"journal" : {
"verbosity" : -1
}
},
"write" : {
"verbosity" : -1
}
}

To modify these settings, you can configure the [Link] (page 722) and
[Link].<name>.verbosity settings in the configuration file (page 721) or set the
logComponentVerbosity (page 755) parameter using the setParameter (page 359) command or use the
[Link]() (page 127) method. For examples, see Configure Log Verbosity Levels (page 784).

118 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link]()

[Link]()
Returns The current database connection.
[Link]() (page 119) runs when the shell initiates. Use this command to test that the mongo
(page 632) shell has a connection to the proper database instance.

[Link]()

[Link]()
Returns the current database name.

[Link]()

[Link]()
Returns A status document, containing the errors.
Deprecated since version 1.6.
This output reports all errors since the last time the database received a resetError (page 262) (also
[Link]() (page 126)) command.
This method provides a wrapper around the getPrevError (page 262) command.

[Link]()

[Link]()
This method provides a wrapper around the database command profile (page 379) and returns the current
profiling level.
Deprecated since version 1.8.4: Use [Link]() (page 119) for related functionality.

[Link]()

[Link]()
Returns The current profile (page 379) level and slowOpThresholdMs (page 743) setting.

[Link]()

Definition
[Link]()
Returns A document with the status of the replica set, using data polled from the oplog. Use this
output when diagnosing issues with replication.

2.1. mongo Shell Methods 119


MongoDB Reference Manual, Release 3.0.7

Output
[Link]
Returns the total size of the oplog in megabytes. This refers to the total amount of space allocated to the oplog
rather than the current size of operations stored in the oplog.
[Link]
Returns the total amount of space used by the oplog in megabytes. This refers to the total amount of space
currently used by operations stored in the oplog rather than the total amount of space allocated.
[Link]
Returns an error message if there are no entries in the oplog.
[Link]
Only present when there are no entries in the oplog. Reports a the number of items or rows in the oplog (e.g. 0).
[Link]
Returns the difference between the first and last operation in the oplog, represented in seconds.
Only present if there are entries in the oplog.
[Link]
Returns the difference between the first and last operation in the oplog, rounded and represented in hours.
Only present if there are entries in the oplog.
[Link]
Returns a time stamp for the first (i.e. earliest) operation in the oplog. Compare this value to the last write
operation issued against the server.
Only present if there are entries in the oplog.
[Link]
Returns a time stamp for the last (i.e. latest) operation in the oplog. Compare this value to the last write operation
issued against the server.
Only present if there are entries in the oplog.
[Link]
Returns a time stamp that reflects reflecting the current time. The shell process generates this value, and the
datum may differ slightly from the server time if youre connecting from a remote host as a result. Equivalent
to Date() (page 205).
Only present if there are entries in the oplog.

[Link]()

Definition
[Link](<database>)
param string database The name of a MongoDB database.

Returns A database object.

Used to return another database without modifying the db variable in the shell environment.

Example You can use [Link]() (page 120) as an alternative to the use <database> helper. This
is particularly useful when writing scripts using the mongo (page 632) shell where the use helper is not available.
Consider the following sequence of operations:

120 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

db = [Link]('users')
[Link]()

This operation sets the db object to point to the database named users, and then returns a count (page 23) of the
collection named active. You can create multiple db objects, that refer to different databases, as in the following
sequence of operations:
users = [Link]('users')
records = [Link]('records')

[Link]()
[Link]()

[Link]()
[Link]()

This operation creates two db objects referring to different databases (i.e. users and records) and then returns a
count (page 23) and an example document (page 45) from one collection in that database (i.e. active and requests
respectively.)

[Link]()

[Link]()
Returns Text output listing common methods on the db object.

[Link]()

[Link]()
New in version 2.2.
Returns A document with information about the underlying system that the mongod (page 603) or
mongos (page 622) runs on. Some of the returned fields are only included on some platforms.
[Link]() (page 121) provides a helper in the mongo (page 632) shell around the hostInfo
(page 384) The output of [Link]() (page 121) on a Linux system will resemble the following:
{
"system" : {
"currentTime" : ISODate("<timestamp>"),
"hostname" : "<hostname>",
"cpuAddrSize" : <number>,
"memSizeMB" : <number>,
"numCores" : <number>,
"cpuArch" : "<identifier>",
"numaEnabled" : <boolean>
},
"os" : {
"type" : "<string>",
"name" : "<string>",
"version" : "<string>"
},
"extra" : {
"versionString" : "<string>",
"libcVersion" : "<string>",
"kernelVersion" : "<string>",
"cpuFrequencyMHz" : "<string>",

2.1. mongo Shell Methods 121


MongoDB Reference Manual, Release 3.0.7

"cpuFeatures" : "<string>",
"pageSize" : <number>,
"numPages" : <number>,
"maxOpenFiles" : <number>
},
"ok" : <return>
}

See hostInfo (page 385) for full documentation of the output of [Link]() (page 121).

[Link]()

[Link]()
Returns A document that describes the role of the mongod (page 603) instance.
If the mongod (page 603) is a member of a replica set, then the ismaster (page 309) and secondary
(page 310) fields report if the instance is the primary or if it is a secondary member of the replica set.

See
isMaster (page 309) for the complete documentation of the output of [Link]() (page 122).

[Link]()

Description
[Link](opid)
Terminates an operation as specified by the operation ID. To find operations and their corresponding IDs, see
[Link]() (page 105).
The [Link]() (page 122) method has the following parameter:
param number opid An operation ID.

Warning: Terminate running operations with extreme caution. Only use [Link]() (page 122) to
terminate operations initiated by clients and do not terminate internal database operations.

[Link]()

[Link]()
Provides a list of all database commands. See the Database Commands (page 219) document for a more exten-
sive index of these options.

[Link]()

[Link]()
[Link]() (page 122) loads all scripts in the [Link] collection for the current
database into the mongo (page 632) shell session.
Documents in the [Link] collection have the following prototype form:

122 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

{ _id : "<name>" , value : <function> } }

The documents in the [Link] collection provide functions that your applications can use in any JavaScript
context with MongoDB in this database. These contexts include $where (page 435) clauses and mapReduce
(page 230) operations.

[Link]()

[Link]()
Ends the current authentication session. This function has no effect if the current session is not authenticated.

Note: If youre not logged in and using authentication, [Link]() (page 123) has no effect.
Changed in version 2.4: Because MongoDB now allows users defined in one database to have privileges on
another database, you must call [Link]() (page 123) while using the same database context that you
authenticated to.
If you authenticated to a database such as users or $external, you must issue [Link]() (page 123)
against this database in order to successfully log out.

Example
Use the use <database-name> helper in the interactive mongo (page 632) shell, or the following
[Link]() (page 120) in the interactive shell or in mongo (page 632) shell scripts to change
the db object:
db = [Link]('<database-name>')

When you have set the database context and db object, you can use the [Link]() (page 123) to log out
of database as in the following operation:
[Link]()

[Link]() (page 123) function provides a wrapper around the database command logout (page 275).

[Link]()

[Link]()
Provides a wrapper around the [Link]() (page 69) method. Returns statistics from every
collection separated by three hyphen characters.

Note: The [Link]() (page 123) in the mongo (page 632) shell does
not return JSON. Use [Link]() (page 123) for manual inspection, and
[Link]() (page 69) in scripts.

See also:
collStats (page 369)

[Link]()

Definition

2.1. mongo Shell Methods 123


MongoDB Reference Manual, Release 3.0.7

[Link]()
Prints a formatted report of the replica set members oplog. The displayed report formats the data returned by
[Link]() (page 119). 7
The output of [Link]() (page 123) is identical to that of
[Link]() (page 180).

Note: The [Link]() (page 123) in the mongo (page 632) shell does
not return JSON. Use [Link]() (page 123) for manual inspection, and
[Link]() (page 119) in scripts.

Output Example The following example is a sample output from the [Link]()
(page 123) method run on the primary:
configured oplog size: 192MB
log length start to end: 65422secs (18.17hrs)
oplog first event time: Mon Jun 23 2014 [Link] GMT-0400 (EDT)
oplog last event time: Tue Jun 24 2014 [Link] GMT-0400 (EDT)
now: Thu Jun 26 2014 [Link] GMT-0400 (EDT)

Output Fields [Link]() (page 123) formats and prints the data returned by
[Link]() (page 119):
configured oplog size Displays the [Link] (page 120) value.
log length start to end Displays the [Link] (page 120) and
[Link] (page 120) values.
oplog first event time Displays the [Link] (page 120).
oplog last event time Displays the [Link] (page 120).
now Displays the [Link] (page 120).
See [Link]() (page 119) for description of the data.

[Link]()

Definition
[Link]()
Prints a formatted report of the sharding configuration and the information regarding existing chunks in a
sharded cluster.
Only use [Link]() (page 124) when connected to a mongos (page 622) instance.
The [Link]() (page 124) method has the following parameter:
param boolean verbose Optional. If true, the method displays details of the document distribu-
tion across chunks when you have 20 or more chunks.
See [Link]() (page 198) for details of the output.

Note: The [Link]() (page 124) in the mongo (page 632) shell does not re-
turn JSON. Use [Link]() (page 124) for manual inspection, and Config Database
(page 711) in scripts.
7 If run on a slave of a master-slave replication, the method calls [Link]() (page 125). See

[Link]() (page 125) for details.

124 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

See also:
[Link]() (page 198)

[Link]()

Definition
[Link]()
Returns a formatted report of the status of a replica set from the perspective of the secondary member of the set.
The output is identical to that of [Link]() (page 181).

Output The following is example output from the [Link]() (page 125) method
issued on a replica set with two secondary members:
source: [Link]
syncedTo: Thu Apr 10 2014 [Link] GMT-0400 (EDT)
0 secs (0 hrs) behind the primary
source: [Link]
syncedTo: Thu Apr 10 2014 [Link] GMT-0400 (EDT)
0 secs (0 hrs) behind the primary

Note: The [Link]() (page 125) in the mongo (page 632) shell does not re-
turn JSON. Use [Link]() (page 125) for manual inspection, and [Link]()
(page 183) in scripts.

A delayed member may show as 0 seconds behind the primary when the inactivity period on the primary is greater
than the slaveDelay (page 314) value.

[Link]()

[Link]()
[Link]() (page 125) provides a wrapper around the database command repairDatabase
(page 360), and has the same effect as the run-time option mongod --repair option, limited to only the
current database. See repairDatabase (page 360) for full documentation.

Warning: During normal operations, only use the repairDatabase (page 360) command and wrappers
including [Link]() (page 125) in the mongo (page 632) shell and mongod --repair, to
compact database files and/or reclaim disk space. Be aware that these operations remove and do not save any
Behavior corrupt data during the repair process.
If you are trying to repair a replica set member, and you have access to an intact copy of your data (e.g. a
recent backup or an intact member of the replica set), you should restore from that intact copy, and not use
repairDatabase (page 360).

When using journaling, there is almost never any need to run repairDatabase (page 360). In the event of an
unclean shutdown, the server will be able to restore the data files to a pristine state automatically.
Changed in version 2.6: The [Link]() (page 125) is now available for secondary as well as primary
members of replica sets.

2.1. mongo Shell Methods 125


MongoDB Reference Manual, Release 3.0.7

[Link]()

[Link]()
Deprecated since version 1.6.
Resets the error message returned by [Link] (page 119) or getPrevError (page 262). Pro-
vides a wrapper around the resetError (page 262) command.

[Link]()

Definition
[Link](command)
Provides a helper to run specified database commands (page 219). This is the preferred method to issue database
commands, as it provides a consistent interface between the shell and drivers.
param document, string command A database command, specified either in document form or
as a string. If specified as a string, [Link]() (page 126) transforms the string into
a document.
New in version 2.6: To specify a time limit in milliseconds, see
[Link]

Behavior [Link]() (page 126) runs the command in the context of the current database. Some com-
mands are only applicable in the context of the admin database, and you must change your db object to before
running these commands.

[Link]()

[Link]()
Provides a wrapper around the buildInfo (page 368) database command. buildInfo (page 368) returns a
document that contains an overview of parameters used to compile this mongod (page 603) instance.

[Link]()

[Link]()
Wraps the getCmdLineOpts (page 378) database command.
Returns a document that reports on the arguments and configuration options used to start the mongod (page 603)
or mongos (page 622) instance.
See Configuration File Options (page 721), mongod (page 603), and mongos (page 622) for additional informa-
tion on available MongoDB runtime options.

[Link]()

[Link]()
Returns a document that provides an overview of the database processs state.
Changed in version 3.0: The server status output no longer includes the workingSet, indexCounters,
and recordStats sections.
This command provides a wrapper around the database command serverStatus (page 386).

126 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Changed in version 2.4: In 2.4 you can dynamically suppress portions of the [Link]()
(page 126) output, or include suppressed sections in a document passed to the [Link]()
(page 126) method, as in the following example:
[Link]( { repl: 0, locks: 0 } )
[Link]( { metrics: 0, locks: 0 } )

serverStatus (page 386) includes all fields by default, except rangeDeleter (page 395) and some content in
the repl (page 392) document.

Note: You may only dynamically include top-level fields from the serverStatus (page 386) document that are
not included by default. You can exclude any field that serverStatus (page 386) includes by default.

See also:
serverStatus (page 386) for complete documentation of the output of this function. For an example of the output,
see [Link]

[Link]()

Definition
[Link]()
New in version 3.0.
Sets a single verbosity level for log messages (page 782).
[Link]() (page 127) has the following form:
[Link](<level>, <component>)

[Link]() (page 127) takes the following parameters:


param int level The log verbosity level.
The verbosity level can range from 0 to 5:
0 is the MongoDBs default log verbosity level, to include Informational (page 783) mes-
sages.
1 to 5 increases the verbosity level to include Debug (page 783) messages.
To inherit the verbosity level of the components parent, you can also specify -1.
param string component Optional. The name of the component for which to specify the log
verbosity level. The component name corresponds to the <name> from the corresponding
[Link].<name>.verbosity setting:
accessControl (page 724)
command (page 725)
control (page 725)
geo (page 725)
index (page 725)
network (page 726)
query (page 726)
replication (page 726)

2.1. mongo Shell Methods 127


MongoDB Reference Manual, Release 3.0.7

sharding (page 726)


storage (page 727)
[Link] (page 727)
write (page 727)
Omit to specify the default verbosity level for all components.

Behavior [Link]() (page 127) sets a single verbosity level. To set multiple verbosity levels in a single
operation, use either the setParameter (page 359) command to set the logComponentVerbosity (page 755)
parameter. You can also specify the verbosity settings in the configuration file (page 721). See Configure Log Verbosity
Levels (page 784) for examples.

Examples

Set Default Verbosity Level Omit the <component> parameter to set the default verbosity for all components;
i.e. the [Link] (page 722) setting. The operation sets the default verbosity to 1:
[Link](1)

Set Verbosity Level for a Component Specify the <component> parameter to set the verbosity for the com-
ponent. The following operation updates the [Link]
(page 727) to 2:
[Link](2, "[Link]" )

[Link]()

Definition
[Link](level, slowms)
Modifies the current database profiler level used by the database profiling system to capture data about perfor-
mance. The method provides a wrapper around the database command profile (page 379).
param integer level Specifies a profiling level, which is either 0 for no profiling, 1 for only slow
operations, or 2 for all operations.
param integer slowms Optional. Sets the threshold in milliseconds for the profile to consider a
query or operation to be slow.
The level chosen can affect performance. It also can allow the server to write the contents of queries to the log,
which might have information security implications for your deployment.
Configure the slowOpThresholdMs (page 743) option to set the threshold for the profiler to consider a query
slow. Specify this value in milliseconds to override the default, 100ms.
mongod (page 603) writes the output of the database profiler to the [Link] collection.
mongod (page 603) prints information about queries that take longer than the slowOpThresholdMs
(page 743) to the log even when the database profiler is not active.

128 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link]()

[Link]()
Shuts down the current mongod (page 603) or mongos (page 622) process cleanly and safely.
This operation fails when the current database is not the admin database.
This command provides a wrapper around the shutdown (page 362).

[Link]()

Description
[Link](scale)
Returns statistics that reflect the use state of a single database.
The [Link]() (page 129) method has the following parameter:
param number scale Optional. The scale at which to deliver results. Unless specified, this com-
mand returns all data in bytes.

Returns A document with statistics reflecting the database systems state. For an explanation of the
output, see dbStats (page 375).

The [Link]() (page 129) method is a wrapper around the dbStats (page 375) database command.

Example The following example converts the returned values to kilobytes:


[Link](1024)

Note: The scale factor rounds values to whole numbers. This can produce unpredictable and unexpected results in
some situations.

[Link]()

[Link]()
Returns The version of the mongod (page 603) or mongos (page 622) instance.

[Link]()

Definition
[Link](<document>)
New in version 2.6.
Performs a preliminary check for upgrade preparedness to 2.6. The helper, available in the 2.6 mongo (page 632)
shell, can run connected to either a 2.4 or a 2.6 server.
The method checks for:
documents with index keys longer than the index key limit (page 880),
documents with illegal field names (page 766),
collections without an _id index, and

2.1. mongo Shell Methods 129


MongoDB Reference Manual, Release 3.0.7

indexes with invalid specifications, such as an index key with an empty or illegal field name.
The method can accept a document parameter which determine the scope of the check:
param document scope Optional. Document to limit the scope of the check to the specified collec-
tion in the database.
Omit to perform the check on all collections in the database.
The optional scope document has the following form:
{
collection: <string>
}

Additional 2.6 changes that affect compatibility with older versions require manual checks and intervention.
See Compatibility Changes in MongoDB 2.6 (page 880) for details.
See also:
[Link]() (page 131)

Behavior [Link]() (page 129) performs collection scans and has an impact on performance. To
mitigate the performance impact:
For sharded clusters, configure to read from secondaries and run the command on the mongos (page 622).
For replica sets, run the command on the secondary members.
[Link]() (page 129) can miss new data during the check when run on a live system with active write
operations.
For index validation, [Link]() (page 129) only supports the check of version 1 indexes and skips the
check of version 0 indexes.
The [Link]() (page 129) checks all of the data stored in the mongod (page 603) instance: the time to
run [Link]() (page 129) depends on the quantity of data stored by mongod (page 603).

Required Access On systems running with authorization (page 736), a user must have access that includes
the find action on all collections, including the system collections (page 718).

Example The following example connects to a secondary running on localhost and runs
[Link]() (page 129) against the employees collection in the records database. Because
the output from the method can be quite large, the example pipes the output to a file.
./mongo --eval "[Link]().setSlaveOk(); [Link]( { collection: 'employees' } )" localhos

Error Output The upgrade check can return the following errors when it encounters incompatibilities in your data:

Index Key Exceed Limit


Document Error: key for index '<indexName>' (<indexSpec>) too long on document: <doc>

To resolve, remove the document. Ensure that the query to remove the document does not specify a condition on the
invalid field or field.

130 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Documents with Illegal Field Names


Document Error: document is no longer valid in 2.6 because <errmsg>: <doc>

To resolve, remove the document and re-insert with the appropriate corrections.

Index Specification Invalid


Index Error: invalid index spec for index '<indexName>': <indexSpec>

To resolve, remove the invalid index and recreate with a valid index specification.

Missing _id Index


Collection Error: lack of _id index on collection: <collectionName>

To resolve, create a unique index on _id.

Warning Output
Warning: upgradeCheck only supports V1 indexes. Skipping index: <indexSpec>

To resolve, remove the invalid index and recreate the index omitting the version specification, or reindex the collection.
Reindex operation may be expensive for collections that have a large amount of data and/or a large number of indexes.

[Link]()

Definition
[Link]()
New in version 2.6.
Performs a preliminary check for upgrade preparedness to 2.6. The helper, available in the 2.6 mongo (page 632)
shell, can run connected to either a 2.4 or a 2.6 server in the admin database.
The method cycles through all the databases and checks for:
documents with index keys longer than the index key limit (page 880),
documents with illegal field names (page 766),
collections without an _id index, and
indexes with invalid specifications, such as an index key with an empty or illegal field name.
Additional 2.6 changes that affect compatibility with older versions require manual checks and intervention.
See Compatibility Changes in MongoDB 2.6 (page 880) for details.
See also:
[Link]() (page 129)

Behavior [Link]() (page 131) performs collection scans and has an impact on perfor-
mance. To mitigate the performance impact:
For sharded clusters, configure to read from secondaries and run the command on the mongos (page 622).
For replica sets, run the command on the secondary members.

2.1. mongo Shell Methods 131


MongoDB Reference Manual, Release 3.0.7

[Link]() (page 131) can miss new data during the check when run on a live system with
active write operations.
For index validation, [Link]() (page 131) only supports the check of version 1 indexes and
skips the check of version 0 indexes.
The [Link]() (page 131) checks all of the data stored in the mongod (page 603) instance:
the time to run [Link]() (page 131) depends on the quantity of data stored by mongod
(page 603).

Required Access On systems running with authorization (page 736), a user must have access that includes
the listDatabases action on all databases and the find action on all collections, including the system collections
(page 718).
You must run the [Link]() (page 131) operation in the admin database.

Example The following example connects to a secondary running on localhost and runs
[Link]() (page 131) against the admin database. Because the output from the method can
be quite large, the example pipes the output to a file.
./mongo --eval "[Link]().setSlaveOk(); [Link]();" localhost/admin | tee /tmp/upgr

Error Output The upgrade check can return the following errors when it encounters incompatibilities in your data:

Index Key Exceed Limit


Document Error: key for index '<indexName>' (<indexSpec>) too long on document: <doc>

To resolve, remove the document. Ensure that the query to remove the document does not specify a condition on the
invalid field or field.

Documents with Illegal Field Names


Document Error: document is no longer valid in 2.6 because <errmsg>: <doc>

To resolve, remove the document and re-insert with the appropriate corrections.

Index Specification Invalid


Index Error: invalid index spec for index '<indexName>': <indexSpec>

To resolve, remove the invalid index and recreate with a valid index specification.

Missing _id Index


Collection Error: lack of _id index on collection: <collectionName>

To resolve, create a unique index on _id.

Warning Output
Warning: upgradeCheck only supports V1 indexes. Skipping index: <indexSpec>

To resolve, remove the invalid index and recreate the index omitting the version specification, or reindex the collection.
Reindex operation may be expensive for collections that have a large amount of data and/or a large number of indexes.

132 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

2.1.4 Query Plan Cache

Query Plan Cache Methods

The PlanCache methods are only accessible from a collections plan cache object. To retrieve the plan cache object,
use the [Link]() (page 133) method.
Name Description
Returns an interface to access the query plan cache object and associated PlanCache
[Link]()
(page 133) methods for a collection.
[Link]() Displays the methods available for a collections query plan cache. Accessible
(page 134) through the plan cache object of a specific collection, i.e.
[Link]().help().
Displays the query shapes for which cached query plans exist. Accessible through
[Link]()
(page 134) the plan cache object of a specific collection, i.e.
[Link]().listQueryShapes().
Displays the cached query plans for the specified query shape. Accessible through
[Link]()
(page 135) the plan cache object of a specific collection, i.e.
[Link]().getPlansByQuery().
Clears the cached query plans for the specified query shape. Accessible through the
[Link]()
(page 136) plan cache object of a specific collection, i.e.
[Link]().clearPlansByQuery()
[Link]() Clears all the cached query plans for a collection. Accessible through the plan
(page 137) cache object of a specific collection, i.e.
[Link]().clear().

[Link]()

Definition
[Link]()
Returns an interface to access the query plan cache for a collection. The interface provides methods to view and
clear the query plan cache.
Returns Interface to access the query plan cache.
The query optimizer only caches the plans for those query shapes that can have more than one viable plan.

Methods The following methods are available through the interface:

2.1. mongo Shell Methods 133


MongoDB Reference Manual, Release 3.0.7

Name Description
[Link]() Displays the methods available for a collections query plan cache. Accessible
(page 134) through the plan cache object of a specific collection, i.e.
[Link]().help().
Displays the query shapes for which cached query plans exist. Accessible through
[Link]()
(page 134) the plan cache object of a specific collection, i.e.
[Link]().listQueryShapes().
Displays the cached query plans for the specified query shape. Accessible through
[Link]()
(page 135) the plan cache object of a specific collection, i.e.
[Link]().getPlansByQuery().
Clears the cached query plans for the specified query shape. Accessible through the
[Link]()
(page 136) plan cache object of a specific collection, i.e.
[Link]().clearPlansByQuery()
[Link]() Clears all the cached query plans for a collection. Accessible through the plan
(page 137) cache object of a specific collection, i.e.
[Link]().clear().

[Link]()

Definition
[Link]()
Displays the methods available to view and modify a collections query plan cache.
The method is only available from the plan cache object (page 133) of a specific collection; i.e.
[Link]().help()
See also:
[Link]() (page 133)

[Link]()

Definition
[Link]()
Displays the query shapes for which cached query plans exist.
The query optimizer only caches the plans for those query shapes that can have more than one viable plan.
The method is only available from the plan cache object (page 133) of a specific collection; i.e.
[Link]().listQueryShapes()

Returns Array of query shape documents.

The method wraps the planCacheListQueryShapes (page 271) command.

Required Access On systems running with authorization (page 736), a user must have access that includes
the planCacheRead action.

Example The following returns the query shapes that have cached plans for the orders collection:
[Link]().listQueryShapes()

134 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

The method returns an array of the query shapes currently in the cache. In the example, the orders collection had
cached query plans associated with the following shapes:
[
{
"query" : { "qty" : { "$gt" : 10 } },
"sort" : { "ord_date" : 1 },
"projection" : { }
},
{
"query" : { "$or" :
[
{ "qty" : { "$gt" : 15 }, "item" : "xyz123" },
{ "status" : "A" }
]
},
"sort" : { },
"projection" : { }
},
{
"query" : { "$or" : [ { "qty" : { "$gt" : 15 } }, { "status" : "A" } ] },
"sort" : { },
"projection" : { }
}
]

See also:
[Link]() (page 133)
[Link]() (page 135)
[Link]() (page 134)
planCacheListQueryShapes (page 271)

[Link]()

Definition
[Link](<query>, <projection>, <sort>)
Displays the cached query plans for the specified query shape.
The query optimizer only caches the plans for those query shapes that can have more than one viable plan.
The method is only available from the plan cache object (page 133) of a specific collection; i.e.
[Link]().getPlansByQuery( <query>, <projection>, <sort> )

The [Link]() (page 135) method accepts the following parameters:


param document query The query predicate of the query shape. Only the structure of the predicate,
including the field names, are significant to the shape; the values in the query predicate are
insignificant.
param document projection Optional. The projection associated with the query shape. Required
if specifying the sort parameter.
param document sort Optional. The sort associated with the query shape.

Returns Array of cached query plans for a query shape.

2.1. mongo Shell Methods 135


MongoDB Reference Manual, Release 3.0.7

To see the query shapes for which cached query plans exist, use the [Link]()
(page 134) method.

Required Access On systems running with authorization (page 736), a user must have access that includes
the planCacheRead action.

Example If a collection orders has the following query shape:


{
"query" : { "qty" : { "$gt" : 10 } },
"sort" : { "ord_date" : 1 },
"projection" : { }
}

The following operation displays the query plan cached for the shape:
[Link]().getPlansByQuery(
{ "qty" : { "$gt" : 10 } },
{ },
{ "ord_date" : 1 }
)

See also:
[Link]() (page 133)
[Link]() (page 134)
[Link]() (page 134)

[Link]()

Definition
[Link](<query>, <projection>, <sort>)
Clears the cached query plans for the specified query shape.
The method is only available from the plan cache object (page 133) of a specific collection; i.e.
[Link]().clearPlansByQuery( <query>, <projection>, <sort> )

The [Link]() (page 136) method accepts the following parameters:


param document query The query predicate of the query shape. Only the structure of the predicate,
including the field names, are significant to the shape; the values in the query predicate are
insignificant.
param document projection Optional. The projection associated with the query shape. Required
if specifying the sort parameter.
param document sort Optional. The sort associated with the query shape.
To see the query shapes for which cached query plans exist, use the [Link]()
(page 134) method.

Required Access On systems running with authorization (page 736), a user must have access that includes
the planCacheWrite action.

136 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Example If a collection orders has the following query shape:


{
"query" : { "qty" : { "$gt" : 10 } },
"sort" : { "ord_date" : 1 },
"projection" : { }
}

The following operation removes the query plan cached for the shape:
[Link]().clearPlansByQuery(
{ "qty" : { "$gt" : 10 } },
{ },
{ "ord_date" : 1 }
)

See also:
[Link]() (page 133)
[Link]() (page 134)
[Link]() (page 137)

[Link]()

Definition
[Link]()
Removes all cached query plans for a collection.
The method is only available from the plan cache object (page 133) of a specific collection; i.e.
[Link]().clear()

For example, to clear the cache for the orders collection:


[Link]().clear()

Required Access On systems running with authorization (page 736), a user must have access that includes
the planCacheWrite action.
See also:
[Link]() (page 133)
[Link]() (page 136)

2.1.5 Bulk Write Operation

Bulk Operation Methods

New in version 2.6.

2.1. mongo Shell Methods 137


MongoDB Reference Manual, Release 3.0.7

Name Description
Bulk() (page 138) Bulk operations builder.
Initializes a Bulk() (page 138) operations builder for an ordered list
[Link]()
(page 140) of operations.
Initializes a Bulk() (page 138) operations builder for an unordered
[Link]()
(page 141) list of operations.
[Link]() (page 141) Adds an insert operation to a list of operations.
[Link]() (page 142) Specifies the query condition for an update or a remove operation.
[Link]() Adds a single document remove operation to a list of operations.
(page 143)
[Link]() (page 143) Adds a multiple document remove operation to a list of operations.
[Link]() Adds a single document replacement operation to a list of operations.
(page 144)
[Link]() Adds a single document update operation to a list of operations.
(page 145)
[Link]() (page 146) Adds a multi update operation to a list of operations.
[Link]() (page 147) Specifies upsert: true for an update operation.
[Link]() (page 150) Executes a list of operations in bulk.
[Link]() Returns an array of write operations executed in the Bulk()
(page 152) (page 138) operations object.
[Link]() (page 153) Returns a JSON document that contains the number of operations and
batches in the Bulk() (page 138) operations object.
[Link]() (page 153) Returns the [Link]() (page 153) results as a string.

Bulk()

Description
Bulk()
New in version 2.6.
Bulk operations builder used to construct a list of write operations to perform in bulk for a single collection.
To instantiate the builder, use either the [Link]() (page 140)
or the [Link]() (page 141) method.

Ordered and Unordered Bulk Operations The builder can construct the list of operations as ordered or unordered.

Ordered Operations With an ordered operations list, MongoDB executes the write operations in the list serially.
If an error occurs during the processing of one of the write operations, MongoDB will return without processing any
remaining write operations in the list.
Use [Link]() (page 140) to create a builder for an ordered list of
write commands.
When executing an ordered (page 140) list of operations, MongoDB groups the operations by the operation
type (page 153) and contiguity; i.e. contiguous operations of the same type are grouped together. For example, if an
ordered list has two insert operations followed by an update operation followed by another insert operation, MongoDB
groups the operations into three separate groups: first group contains the two insert operations, second group contains
the update operation, and the third group contains the last insert operation. This behavior is subject to change in future
versions.
Each group of operations can have at most 1000 operations (page 765). If a group exceeds this limit
(page 765), MongoDB will divide the group into smaller groups of 1000 or less. For example, if the bulk opera-
tions list consists of 2000 insert operations, MongoDB creates 2 groups, each with 1000 operations.

138 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

The sizes and grouping mechanics are internal performance details and are subject to change in future versions.
To see how the operations are grouped for a bulk operation execution, call [Link]() (page 152)
after the execution.
Executing an ordered (page 140) list of operations on a sharded collection will generally be slower than executing
an unordered (page 141) list since with an ordered list, each operation must wait for the previous operation to finish.

Unordered Operations With an unordered operations list, MongoDB can execute in parallel, as well as in a nonde-
terministic order, the write operations in the list. If an error occurs during the processing of one of the write operations,
MongoDB will continue to process remaining write operations in the list.
Use [Link]() (page 141) to create a builder for an unordered list
of write commands.
When executing an unordered (page 141) list of operations, MongoDB groups the operations. With an unordered
bulk operation, the operations in the list may be reordered to increase performance. As such, applications should not
depend on the ordering when performing unordered (page 141) bulk operations.
Each group of operations can have at most 1000 operations (page 765). If a group exceeds this limit
(page 765), MongoDB will divide the group into smaller groups of 1000 or less. For example, if the bulk opera-
tions list consists of 2000 insert operations, MongoDB creates 2 groups, each with 1000 operations.
The sizes and grouping mechanics are internal performance details and are subject to change in future versions.
To see how the operations are grouped for a bulk operation execution, call [Link]() (page 152)
after the execution.

Methods The Bulk() (page 138) builder has the following methods:
Name Description
[Link]() Adds an insert operation to a list of operations.
(page 141)
[Link]() (page 142) Specifies the query condition for an update or a remove operation.
[Link]() Adds a single document remove operation to a list of operations.
(page 143)
[Link]() Adds a multiple document remove operation to a list of operations.
(page 143)
[Link]()Adds a single document replacement operation to a list of operations.
(page 144)
[Link]() Adds a single document update operation to a list of operations.
(page 145)
[Link]() Adds a multi update operation to a list of operations.
(page 146)
[Link]() Specifies upsert: true for an update operation.
(page 147)
[Link]() Executes a list of operations in bulk.
(page 150)
[Link]() Returns an array of write operations executed in the Bulk() (page 138)
(page 152) operations object.
[Link]() Returns a JSON document that contains the number of operations and batches in
(page 153) the Bulk() (page 138) operations object.
[Link]() Returns the [Link]() (page 153) results as a string.
(page 153)

2.1. mongo Shell Methods 139


MongoDB Reference Manual, Release 3.0.7

[Link]()

Definition
[Link]()
Initializes and returns a new Bulk() (page 138) operations builder for a collection. The builder constructs an
ordered list of write operations that MongoDB executes in bulk.
Returns new Bulk() (page 138) operations builder object.

Behavior

Order of Operation With an ordered operations list, MongoDB executes the write operations in the list serially.

Execution of Operations When executing an ordered (page 140) list of operations, MongoDB groups the opera-
tions by the operation type (page 153) and contiguity; i.e. contiguous operations of the same type are grouped
together. For example, if an ordered list has two insert operations followed by an update operation followed by an-
other insert operation, MongoDB groups the operations into three separate groups: first group contains the two insert
operations, second group contains the update operation, and the third group contains the last insert operation. This
behavior is subject to change in future versions.
Each group of operations can have at most 1000 operations (page 765). If a group exceeds this limit
(page 765), MongoDB will divide the group into smaller groups of 1000 or less. For example, if the bulk opera-
tions list consists of 2000 insert operations, MongoDB creates 2 groups, each with 1000 operations.
The sizes and grouping mechanics are internal performance details and are subject to change in future versions.
To see how the operations are grouped for a bulk operation execution, call [Link]() (page 152)
after the execution.
Executing an ordered (page 140) list of operations on a sharded collection will generally be slower than executing
an unordered (page 141) list since with an ordered list, each operation must wait for the previous operation to finish.

Error Handling If an error occurs during the processing of one of the write operations, MongoDB will return
without processing any remaining write operations in the list.

Examples The following initializes a Bulk() (page 138) operations builder on the users collection, adds a series
of write operations, and executes the operations:
var bulk = [Link]();
[Link]( { user: "abc123", status: "A", points: 0 } );
[Link]( { user: "ijk123", status: "A", points: 0 } );
[Link]( { user: "mop123", status: "P", points: 0 } );
[Link]( { status: "D" } ).remove();
[Link]( { status: "P" } ).update( { $set: { comment: "Pending" } } );
[Link]();

See also:
[Link]() (page 141)
[Link]() (page 142)
[Link]() (page 143)
[Link]() (page 150)

140 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link]()

Definition
[Link]()
New in version 2.6.
Initializes and returns a new Bulk() (page 138) operations builder for a collection. The builder constructs an
unordered list of write operations that MongoDB executes in bulk.

Behavior

Order of Operation With an unordered operations list, MongoDB can execute in parallel the write operations in the
list and in any order. If the order of operations matter, use [Link]()
(page 140) instead.

Execution of Operations When executing an unordered (page 141) list of operations, MongoDB groups the
operations. With an unordered bulk operation, the operations in the list may be reordered to increase performance. As
such, applications should not depend on the ordering when performing unordered (page 141) bulk operations.
Each group of operations can have at most 1000 operations (page 765). If a group exceeds this limit
(page 765), MongoDB will divide the group into smaller groups of 1000 or less. For example, if the bulk opera-
tions list consists of 2000 insert operations, MongoDB creates 2 groups, each with 1000 operations.
The sizes and grouping mechanics are internal performance details and are subject to change in future versions.
To see how the operations are grouped for a bulk operation execution, call [Link]() (page 152)
after the execution.

Error Handling If an error occurs during the processing of one of the write operations, MongoDB will continue to
process remaining write operations in the list.

Example The following initializes a Bulk() (page 138) operations builder and adds a series of insert operations to
add multiple documents:
var bulk = [Link]();
[Link]( { user: "abc123", status: "A", points: 0 } );
[Link]( { user: "ijk123", status: "A", points: 0 } );
[Link]( { user: "mop123", status: "P", points: 0 } );
[Link]();

See also:
[Link]() (page 140)
Bulk() (page 138)
[Link]() (page 141)
[Link]() (page 150)

[Link]()

Description

2.1. mongo Shell Methods 141


MongoDB Reference Manual, Release 3.0.7

[Link](<document>)
New in version 2.6.
Adds an insert operation to a bulk operations list.
[Link]() (page 141) accepts the following parameter:
param document doc Document to insert. The size of the document must be less than or equal to
the maximum BSON document size (page 759).

Example The following initializes a Bulk() (page 138) operations builder for the items collection and adds a
series of insert operations to add multiple documents:
var bulk = [Link]();
[Link]( { item: "abc123", defaultQty: 100, status: "A", points: 100 } );
[Link]( { item: "ijk123", defaultQty: 200, status: "A", points: 200 } );
[Link]( { item: "mop123", defaultQty: 0, status: "P", points: 0 } );
[Link]();

See also:
[Link]() (page 141)
[Link]() (page 140)
[Link]() (page 150)

[Link]()

Description
[Link](<query>)
New in version 2.6.
Specifies a query condition for an update or a remove operation.
[Link]() (page 142) accepts the following parameter:
param document query Specifies a query condition using Query Selectors (page 413) to select doc-
uments for an update or a remove operation. To specify all documents, use an empty document
{}.
With update operations, the sum of the query document and the update document must be less
than or equal to the maximum BSON document size (page 759).
With remove operations, the query document must be less than or equal to the maximum BSON
document size (page 759).
Use [Link]() (page 142) with the following write operations:
[Link]() (page 143)
[Link]() (page 143)
[Link]() (page 144)
[Link]() (page 145)
[Link]() (page 146)

142 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Example The following example initializes a Bulk() (page 138) operations builder for the items collection and
adds a remove operation and an update operation to the list of operations. The remove operation and the update
operation use the [Link]() (page 142) method to specify a condition for their respective actions:
var bulk = [Link]();
[Link]( { status: "D" } ).remove();
[Link]( { status: "P" } ).update( { $set: { points: 0 } } )
[Link]();

See also:
[Link]() (page 141)
[Link]() (page 140)
[Link]() (page 150)

[Link]()

Description
[Link]()
New in version 2.6.
Adds a single document remove operation to a bulk operations list. Use the [Link]() (page 142)
method to specify the condition that determines which document to remove. The [Link]()
(page 143) limits the removal to one document. To remove multiple documents, see [Link]()
(page 143).

Example The following example initializes a Bulk() (page 138) operations builder for the items collection and
adds two [Link]() (page 143) operations to the list of operations.
Each remove operation removes just one document: one document with the status equal to "D" and another
document with the status equal to "P".
var bulk = [Link]();
[Link]( { status: "D" } ).removeOne();
[Link]( { status: "P" } ).removeOne();
[Link]();

See also:
[Link]() (page 141)
[Link]() (page 140)
[Link]() (page 142)
[Link]() (page 143)
[Link]() (page 150)
All Bulk Methods (page 139)

[Link]()

Description

2.1. mongo Shell Methods 143


MongoDB Reference Manual, Release 3.0.7

[Link]()
New in version 2.6.
Adds a remove operation to a bulk operations list. Use the [Link]() (page 142) method to spec-
ify the condition that determines which documents to remove. The [Link]() (page 143)
method removes all matching documents in the collection. To limit the remove to a single document, see
[Link]() (page 143).

Example The following example initializes a Bulk() (page 138) operations builder for the items collection and
adds a remove operation to the list of operations. The remove operation removes all documents in the collection where
the status equals "D":
var bulk = [Link]();
[Link]( { status: "D" } ).remove();
[Link]();

See also:
[Link]() (page 141)
[Link]() (page 140)
[Link]() (page 142)
[Link]() (page 143)
[Link]() (page 150)

[Link]()

Description
[Link](<document>)
New in version 2.6.
Adds a single document replacement operation to a bulk operations list. Use the [Link]()
(page 142) method to specify the condition that determines which document to replace. The
[Link]() (page 144) method limits the replacement to a single document.
[Link]() (page 144) accepts the following parameter:
param document replacement A replacement document that completely replaces the existing doc-
ument. Contains only field and value pairs.
The sum of the associated <query> document from the [Link]() (page 142) and the
replacement document must be less than or equal to the maximum BSON document size
(page 759).
To specify an upsert for this operation, see [Link]() (page 147).

Example The following example initializes a Bulk() (page 138) operations builder for the items collection, and
adds various replaceOne (page 144) operations to the list of operations.
var bulk = [Link]();
[Link]( { item: "abc123" } ).replaceOne( { item: "abc123", status: "P", points: 100 } );
[Link]();

See also:
[Link]() (page 141)

144 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

[Link]() (page 140)


[Link]() (page 142)
[Link]() (page 150)
All Bulk Methods (page 139)

[Link]()

Description
[Link](<update>)
New in version 2.6.
Adds a single document update operation to a bulk operations list. The operation can either replace an existing
document or update specific fields in an existing document.
Use the [Link]() (page 142) method to specify the condition that determines which document to update.
The [Link]() (page 145) method limits the update or replacement to a single document.
To update multiple documents, see [Link]() (page 146).
[Link]() (page 145) accepts the following parameter:
param document update An update document that updates specific fields or a replacement docu-
ment that completely replaces the existing document.
An update document only contains update operator (page 464) expressions. A replacement
document contains only field and value pairs.
The sum of the associated <query> document from the [Link]() (page 142) and the
update/replacement document must be less than or equal to the maximum BSON document
size.
To specify an upsert: true for this operation, see [Link]() (page 147).

Behavior

Update Specific Fields If the <update> document contains only update operator (page 464) expressions, as in:
{
$set: { status: "D" },
points: { $inc: 2 }
}

Then, [Link]() (page 145) updates only the corresponding fields, status and points, in the
document.

Replace a Document If the <update> document contains only field:value expressions, as in:
{
item: "TBD",
points: 0,
inStock: true,
status: "I"
}

2.1. mongo Shell Methods 145


MongoDB Reference Manual, Release 3.0.7

Then, [Link]() (page 145) replaces the matching document with the <update> document
with the exception of the _id field. The [Link]() (page 145) method does not replace the _id
value.

Example The following example initializes a Bulk() (page 138) operations builder for the items collection, and
adds various updateOne (page 145) operations to the list of operations.
var bulk = [Link]();
[Link]( { status: "D" } ).updateOne( { $set: { status: "I", points: "0" } } );
[Link]( { item: null } ).updateOne(
{
item: "TBD",
points: 0,
inStock: true,
status: "I"
}
);
[Link]();

See also:
[Link]() (page 141)
[Link]() (page 140)
[Link]() (page 142)
[Link]() (page 146)
[Link]() (page 150)
All Bulk Methods (page 139)

[Link]()

Description
[Link](<update>)
New in version 2.6.
Adds a multi update operation to a bulk operations list. The method updates specific fields in existing docu-
ments.
Use the [Link]() (page 142) method to specify the condition that determines which documents to up-
date. The [Link]() (page 146) method updates all matching documents. To specify a single
document update, see [Link]() (page 145).
[Link]() (page 146) accepts the following parameter:
param document update Specifies the fields to update. Only contains update operator (page 464)
expressions.
The sum of the associated <query> document from the [Link]() (page 142) and
the update document must be less than or equal to the maximum BSON document size
(page 759).
To specify upsert: true for this operation, see [Link]() (page 147). With
[Link]() (page 147), if no documents match the [Link]() (page 142) query condi-
tion, the update operation inserts only a single document.

146 Chapter 2. Interfaces Reference


MongoDB Reference Manual, Release 3.0.7

Example The following example initializes a Bulk() (page 138) operations builder for the items collection, an