MongoDB Reference Manual
MongoDB Reference Manual
Release 2.8.0-rc3
MongoDB Documentation Project
December 18, 2014
2
Contents
1
2
About MongoDB Documentation
1.1 License . . . . . . . . . . . . . . . . . . .
1.2 Editions . . . . . . . . . . . . . . . . . . .
1.3 Version and Revisions . . . . . . . . . . .
1.4 Report an Issue or Make a Change Request
1.5 Contribute to the Documentation . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Interfaces Reference
2.1 mongo Shell Methods
2.2 Database Commands .
2.3 Operators . . . . . . .
2.4 Aggregation Reference
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
21
. 21
. 210
. 400
. 564
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
3
3
3
4
4
4
3
MongoDB and SQL Interface Comparisons
575
3.1 SQL to MongoDB Mapping Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
3.2 SQL to Aggregation Mapping Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
4
Program and Tool Reference Pages
583
4.1 MongoDB Package Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
5
Internal Metadata
5.1 Config Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.2 The local Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.3 System Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
681
681
686
688
6
General System Reference
6.1 Exit Codes and Statuses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.2 MongoDB Limits and Thresholds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.3 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
691
691
692
698
7
Release Notes
7.1 Current Development Release .
7.2 Current Stable Release . . . . .
7.3 Previous Stable Releases . . . .
7.4 Other MongoDB Release Notes
709
709
726
771
817
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
i
ii
MongoDB Reference Manual, Release 2.8.0-rc3
This document contains all of the reference material from the MongoDB Manual, reflecting the 2.8.0-rc3 release.
See the full manual, for complete documentation of MongoDB, it’s operation, and use.
Contents
1
MongoDB Reference Manual, Release 2.8.0-rc3
2
Contents
CHAPTER 1
About MongoDB Documentation
The MongoDB Manual1 contains comprehensive documentation on the MongoDB document-oriented database management system. This page describes the manual’s licensing, editions, and versions, and describes how to make a
change request and how to contribute to the manual.
For more information on MongoDB, see MongoDB: A Document Oriented Database2 . To download MongoDB, see
the downloads page3 .
1.1 License
This manual is licensed under a Creative Commons “Attribution-NonCommercial-ShareAlike 3.0 Unported4 ” (i.e.
“CC-BY-NC-SA”) license.
The MongoDB Manual is copyright В© 2011-2014 MongoDB, Inc.
1.2 Editions
In addition to the MongoDB Manual5 , you can also access this content in the following editions:
• ePub Format6
• Single HTML Page7
• PDF Format8 (without reference.)
• HTML tar.gz9
You also can access PDF files that contain subsets of the MongoDB Manual:
• MongoDB Reference Manual10
• MongoDB CRUD Operations11
1 http://docs.mongodb.org/manual/#
2 http://www.mongodb.org/about/
3 http://www.mongodb.org/downloads
4 http://creativecommons.org/licenses/by-nc-sa/3.0/
5 http://docs.mongodb.org/manual/#
6 http://docs.mongodb.org/master/MongoDB-manual.epub
7 http://docs.mongodb.org/master/single/
8 http://docs.mongodb.org/master/MongoDB-manual.pdf
9 http://docs.mongodb.org/master/manual.tar.gz
10 http://docs.mongodb.org/master/MongoDB-reference-manual.pdf
11 http://docs.mongodb.org/master/MongoDB-crud-guide.pdf
3
MongoDB Reference Manual, Release 2.8.0-rc3
• Data Models for MongoDB12
• MongoDB Data Aggregation13
• Replication and MongoDB14
• Sharding and MongoDB15
• MongoDB Administration16
• MongoDB Security17
MongoDB Reference documentation is also available as part of dash18 . You can also access the MongoDB Man
Pages19 which are also distributed with the official MongoDB Packages.
1.3 Version and Revisions
This version of the manual reflects version 2.8 of MongoDB.
See the MongoDB Documentation Project Page20 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 repository21 .
This
edition
reflects
“master”
branch
of
the
documentation
as
of
the
“d6c735900e4892f1cf4d7a89721188a7c9bad6f3” revision. This branch is explicitly accessible via
“http://docs.mongodb.org/master” and you can always reference the commit of the current manual in the release.txt22
file.
The most up-to-date, current,
“http://docs.mongodb.org/manual/”.
and
stable
version
of
the
manual
is
always
available
at
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 Jira23 .
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.
12 http://docs.mongodb.org/master/MongoDB-data-models-guide.pdf
13 http://docs.mongodb.org/master/MongoDB-aggregation-guide.pdf
14 http://docs.mongodb.org/master/MongoDB-replication-guide.pdf
15 http://docs.mongodb.org/master/MongoDB-sharding-guide.pdf
16 http://docs.mongodb.org/master/MongoDB-administration-guide.pdf
17 http://docs.mongodb.org/master/MongoDB-security-guide.pdf
18 http://kapeli.com/dash
19 http://docs.mongodb.org/master/manpages.tar.gz
20 http://docs.mongodb.org
21 https://github.com/mongodb/docs
22 http://docs.mongodb.org/master/release.txt
23 https://jira.mongodb.org/browse/DOCS
4
Chapter 1. About MongoDB Documentation
MongoDB Reference Manual, Release 2.8.0-rc3
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 Agreement24 , and
• join the mongodb-translators25 user group.
The mongodb-translators26 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 6)
• MongoDB Manual Organization (page 15)
• MongoDB Documentation Practices and Processes (page 12)
• MongoDB Documentation Build System (page 16)
The entire documentation source for this manual is available in the mongodb/docs repository27 , which is one of the
MongoDB project repositories on GitHub28 .
To contribute to the documentation, you can open a GitHub account29 , fork the mongodb/docs repository30 , make a
change, and issue a pull request.
In order for the documentation team to accept your change, you must complete the MongoDB Contributor Agreement31 .
You can clone the repository by issuing the following command at your system shell:
git clone git://github.com/mongodb/docs.git
1.5.2 About the Documentation Process
The MongoDB Manual uses Sphinx32 , a sophisticated documentation engine built upon Python Docutils33 . The original reStructured Text34 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:
24 http://www.mongodb.com/legal/contributor-agreement
25 http://groups.google.com/group/mongodb-translators
26 http://groups.google.com/group/mongodb-translators
27 https://github.com/mongodb/docs
28 http://github.com/mongodb
29 https://github.com/
30 https://github.com/mongodb/docs
31 http://www.mongodb.com/contributor
32 http://sphinx-doc.org//
33 http://docutils.sourceforge.net/
34 http://docutils.sourceforge.net/rst.html
1.5. Contribute to the Documentation
5
MongoDB Reference Manual, Release 2.8.0-rc3
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 15).
Document History
2011-09-27: Document created with a (very) rough list of style guidelines, conventions, and questions.
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
scribes the material covered in the document.
Allow the path of the file within the
ument tree to add some of the required context/categorization.
For example it’s
ceptable
to
have
http://docs.mongodb.org/manual/core/sharding.rst
http://docs.mongodb.org/manual/administration/sharding.rst.
dedocacand
– For tutorials, the full title of the document should be in the file name.
For example,
http://docs.mongodb.org/manual/tutorial/replace-one-configuration-server-in-a-shard
• 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.
6
Chapter 1. About MongoDB Documentation
MongoDB Reference Manual, Release 2.8.0-rc3
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.
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, it’s 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 Manual’s
conf.py 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 http://docs.mongodb.org/manual/tutorial/convert-replica-set-to-replicated-shard-c
procedure if you have an existing replica set.
Type this:
To deploy a sharded cluster for an existing replica set, see http://docs.mongodb.org/manual/tutorial/convert-r
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.
1.5. Contribute to the Documentation
7
MongoDB Reference Manual, Release 2.8.0-rc3
– 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.”
• 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. compound 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 ..
8
code-block::
[language] in footnotes.
Chapter 1. About MongoDB Documentation
MongoDB Reference Manual, Release 2.8.0-rc3
• 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.
1.5. Contribute to the Documentation
9
MongoDB Reference Manual, Release 2.8.0-rc3
10
Chapter 1. About MongoDB Documentation
MongoDB Reference Manual, Release 2.8.0-rc3
Jargon and Common Terms
Preferred
Term
document
Concept
Dispreferred
Alternatives
Notes
A single, top-level object/record
in a MongoDB collection.
record, object,
row
Prefer document over object because of
concerns about cross-driver language handling
of objects. Reserve record for “allocation” of
storage. Avoid “row,” as possible.
Avoid genericizing “database.” Avoid using
database to refer to a server process or a data
set. This applies both to the datastoring
contexts as well as other (related) operational
contexts (command context,
authentication/authorization context.)
Avoid using instance, unless it modifies
something specifically. Having a descriptor for
a process/instance makes it possible to avoid
needing to make mongod or mongos plural.
Server and node are both vague and
contextually difficult to disambiguate with
regards to application servers, and underlying
hardware.
Avoid introducing unrelated terms for a single
field. In the documentation we’ve rarely had to
discuss the identifier of a field, so the extra
word here isn’t burdensome.
Use to emphasize the difference between the
name of a field and its value For example,
“_id” is the field and the default value is an
ObjectId.
databaseA group of collections. Refers to
a group of data files. This is the
“logical” sense of the term
“database.”
instance
A daemon process. (e.g. mongos
or mongod)
process
(acceptable
sometimes), node
(never
acceptable),
server.
field
name
The identifier of a value in a
document.
key, column
field/value
The name/value pair that
describes a unit of data in
MongoDB.
key, slot, attribute
value
MongoDB
The data content of a field.
A group of processes, or
deployment that implement the
MongoDB interface.
data
mongo,
mongodb, cluster
subAn embedded or nested
documentdocument within a document or
an array.
mapAn operation performed by the
reduce mapReduce command.
embedded
document, nested
document
mapReduce, map
reduce,
map/reduce
grid, shard
cluster, set,
deployment
cluster
A sharded cluster.
sharded A sharded cluster.
cluster
replica A deployment of replicating
set
mongod programs that provide
redundancy and automatic
failover.
deA group of MongoDB processes,
ployor a standalone
1.5. Contribute
to the mongod
Documentation
ment
instance.
data
The collection of physical
set
databases provided by a
Stylistic preference, mostly. In some cases it’s
useful to be able to refer generically to
instances (that may be either mongod or
mongos.)
Avoid confusion with the command, shell
helper, and driver interfaces. Makes it possible
to discuss the operation generally.
Cluster is a great word for a group of
processes; however, it’s important to avoid
letting the term become generic. Do not use for
any group of MongoDB processes or
deployments.
shard cluster,
cluster, sharded
system
set, replication
deployment
cluster, system
database, data
Typically in the form MongoDB deployment.
Includes standalones, replica sets and sharded 11
clusters.
Important to keep the distinction between the
data provided by a mongod or a sharded cluster
MongoDB Reference Manual, Release 2.8.0-rc3
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 Documents.”
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”.
• “sub-document” describes a nested document.
Other Terms
• Use example.net (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 sub-documents, in practice, users should only store
coordinates in arrays. (See: DOCS-4135 .)
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 jira.mongodb.org36 .
Err on the side of creating a larger number of discrete commits rather than bundling large set of changes into one
commit.
35 https://jira.mongodb.org/browse/DOCS-41
36 http://jira.mongodb.org/
12
Chapter 1. About MongoDB Documentation
MongoDB Reference Manual, Release 2.8.0-rc3
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 project37 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 GitHub38 , fork the mongodb/docs repository39 , 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 Sphinx40 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.
37 https://jira.mongodb.org/browse/DOCS
38 https://github.com/
39 https://github.com/mongodb/docs
40 http://sphinx.pocoo.org/
1.5. Contribute to the Documentation
13
MongoDB Reference Manual, Release 2.8.0-rc3
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 MongoDB.org Wiki contains a wealth of information. As the transition to the Manual (i.e. this project and
resource) continues, it’s 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 information in question.
At this point, update the relevant Jira case with the target that you’ve 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. Depending 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.”
14
Chapter 1. About MongoDB Documentation
MongoDB Reference Manual, Release 2.8.0-rc3
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 you’re not a usual contributor to the documentation and would like to review something, you
can submit reviews in any of the following methods:
• If you’re 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:
https://github.com/mongodb/docs/pull/[pull-request-id]/files
Replace [pull-request-id] with the identifier of the pull request. Make all comments inline, using
GitHub’s 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 DOCS41 project. These are better for more general changes that aren’t
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 you’re
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 file’s current location, or if you want to add new
documentation but aren’t sure how to integrate it into the existing resource.
If you have questions, don’t hesitate to open a ticket in the Documentation Jira Project42 or contact the documentation
team43 .
41 http://jira.mongodb.org/browse/DOCS
42 https://jira.mongodb.org/browse/DOCS
43 [email protected]
1.5. Contribute to the Documentation
15
MongoDB Reference Manual, Release 2.8.0-rc3
Global Organization
Indexes
and
Experience The
documentation
project
has
two
“index
files”:
http://docs.mongodb.org/manual/contents.txt and http://docs.mongodb.org/manual/index.txt.
The “contents” file provides the documentation’s 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 contents.txt and index.txt, 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 toctree44 structure. However, in order to annotate
the table of contents and provide additional flexibility, the MongoDB documentation generates toctree45 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 toctree46 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
toctree47 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:
44 http://sphinx-doc.org/markup/toctree.html#directive-toctree
45 http://sphinx-doc.org/markup/toctree.html#directive-toctree
46 http://sphinx-doc.org/markup/toctree.html#directive-toctree
47 http://sphinx-doc.org/markup/toctree.html#directive-toctree
16
Chapter 1. About MongoDB Documentation
MongoDB Reference Manual, Release 2.8.0-rc3
• GNU Make
• GNU Tar
• Python
• Git
• Sphinx (documentation management toolchain)
• Pygments (syntax highlighting)
• PyYAML (for the generated tables)
• Droopy (Python package for static text analysis)
• Fabric (Python package for scripting and orchestration)
• Inkscape (Image generation.)
• python-argparse (For Python 2.6.)
• LaTeX/PDF LaTeX (typically texlive; for building PDFs)
• Common Utilities (rsync, tar, gzip, sed)
OS X Install Sphinx, Docutils, and their dependencies with easy_install the following command:
easy_install Sphinx Jinja2 Pygments docutils
PyYAML droopy fabric
Feel free to use pip rather than easy_install to install python packages.
To generate the images used in the documentation, download and install Inkscape48 .
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 MacTeX49 . This is only required to build PDFs.
Arch Linux Install packages from the system repositories with the following command:
pacman -S python2-sphinx python2-yaml inkscape python2-pip
Then install the following Python packages:
pip install droopy fabric
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 python-sphinx python-yaml python-argparse inkscape python-pip
Then install the following Python packages:
48 http://inkscape.org/download/
49 http://www.tug.org/mactex/2011/
1.5. Contribute to the Documentation
17
MongoDB Reference Manual, Release 2.8.0-rc3
pip install droopy fabric
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
Setup and Configuration Clone the repository:
git clone git://github.com/mongodb/docs.git
Then run the bootstrap.py script in the docs/ repository, to configure the build dependencies:
python bootstrap.py
This downloads and configures the mongodb/docs-tools50 repository, which contains the authoritative build system
shared between branches of the MongoDB Manual and other MongoDB documentation projects.
You can run bootstrap.py regularly to update build system.
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. Requires access production or staging environment.
push-all; stage-all Uploads the entire content of build/public/ to the web servers.
publish. Not used in common practice.
Depends on
push-with-delete; stage-with-delete Modifies the action of push and stage to remove remote file
that don’t 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 Sphinx’s 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 .tar.gz file of the build outputs for inclusion in the final releases.
50 http://github.com/mongodb/docs-tools/
18
Chapter 1. About MongoDB Documentation
MongoDB Reference Manual, Release 2.8.0-rc3
Build Mechanics and Tools
Internally the build system has a number of components and processes. See the docs-tools README51 for more
information on the internals. This section documents a few of these components from a very high level and lists useful
operations for contributors to the documentation.
Fabric Fabric is an orchestration and scripting package for Python. The documentation uses Fabric to handle the
deployment of the build products to the web servers and also unifies a number of independent build operations. Fabric
commands have the following form:
fab <module>.<task>[:<argument>]
The <argument> is optional in most cases. Additionally some tasks are available at the root level, without a module.
To see a full list of fabric tasks, use the following command:
fab -l
You can chain fabric tasks on a single command line, although this doesn’t always make sense.
Important fabric tasks include:
tools.bootstrap Runs the bootstrap.py script. Useful for re-initializing the repository without needing to
be in root of the repository.
tools.dev; tools.reset tools.dev switches the origin remote of the docs-tools checkout in build
directory, to ../docs-tools to facilitate build system testing and development. tools.reset resets the
origin remote for normal operation.
tools.conf tools.conf returns the content of the configuration object for the current project. These data are
useful during development.
stats.report:<filename> Returns, a collection of readability statistics.
source/ tree.
Specify file names relative to
make Provides a thin wrapper around Make calls. Allows you to start make builds from different locations in the
project repository.
process.refresh_dependencies Updates the time stamp of .txt source files with changed include files, to
facilitate Sphinx’s incremental rebuild process. This task runs internally as part of the build process.
Buildcloth Buildcloth52 is a meta-build tool, used to generate Makefiles programmatically. This makes the build
system easier to maintain, and makes it easier to use the same fundamental code to generate various branches of the
Manual as well as related documentation projects. See makecloth/ in the docs-tools repository53 for the relevant code.
Running make with no arguments will regenerate these parts of the build system automatically.
Rstcloth Rstcloth54 is a library for generating reStructuredText programmatically. This makes it possible to generate
content for the documentation, such as tables, tables of contents, and API reference material programmatically and
transparently. See rstcloth/ in the docs-tools repository55 for the relevant code.
If you have any questions, please feel free to open a Jira Case56 .
51 https://github.com/mongodb/docs-tools/blob/master/README.rst
52 https://pypi.python.org/pypi/buildcloth/
53 https://github.com/mongodb/docs-tools/tree/master/makecloth
54 https://pypi.python.org/pypi/rstcloth
55 https://github.com/mongodb/docs-tools/tree/master/rstcloth
56 https://jira.mongodb.org/browse/DOCS
1.5. Contribute to the Documentation
19
MongoDB Reference Manual, Release 2.8.0-rc3
20
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
db.collection.aggregate() (page 22)
db.collection.copyTo() (page 25)
db.collection.count() (page 26)
db.collection.createIndex() (page 27)
db.collection.dataSize() (page 28)
db.collection.distinct() (page 28)
db.collection.drop() (page 28)
db.collection.dropIndex() (page 29)
db.collection.dropIndexes() (page 30)
db.collection.ensureIndex() (page 30)
db.collection.explain() (page 33)
db.collection.find() (page 36)
db.collection.findAndModify() (page 42)
db.collection.findOne() (page 46)
db.collection.getIndexStats() (page 47)
db.collection.getIndexes() (page 48)
db.collection.getShardDistribution() (page 49)
db.collection.getShardVersion() (page 51)
db.collection.group() (page 51)
db.collection.indexStats() (page 54)
db.collection.insert() (page 55)
db.collection.isCapped() (page 58)
db.collection.mapReduce() (page 58)
Description
Provides access to the aggregation pipeline.
Wraps eval (page 237) to copy data between collections in a sing
Wraps count (page 213) to return a count of the number of docum
Builds an index on a collection. Use db.collection.ensure
Returns the size of the collection. Wraps the size (page 349) field
Returns an array of documents that have distinct values for the spec
Removes the specified collection from the database.
Removes a specified index on a collection.
Removes all indexes on a collection.
Creates an index if it does not currently exist. If the index exists en
Returns information on the query execution of various methods.
Performs a query on a collection and returns a cursor object.
Atomically modifies and returns a single document.
Performs a query and returns a single document.
Renders a human-readable view of the data collected by indexSt
Returns an array of documents that describe the existing indexes on
For collections in sharded clusters, db.collection.getShar
Internal diagnostic method for shard cluster.
Provides simple data aggregation function. Groups documents in a
Renders a human-readable view of the data collected by indexSt
Creates a new document in a collection.
Reports if a collection is a capped collection.
Performs map-reduce style data aggregation.
21
MongoDB Reference Manual, Release 2.8.0-rc3
Name
db.collection.reIndex() (page 65)
db.collection.remove() (page 66)
db.collection.renameCollection() (page 69)
db.collection.save() (page 70)
db.collection.stats() (page 71)
db.collection.storageSize() (page 72)
db.collection.totalIndexSize() (page 72)
db.collection.totalSize() (page 72)
db.collection.update() (page 72)
db.collection.validate() (page 79)
Table 2.1 – continued from pre
Description
Rebuilds all existing indexes on a collection.
Deletes documents from a collection.
Changes the name of a collection.
Provides a wrapper around an insert() (page 55) and update(
Reports on the state of a collection. Provides a wrapper around the
Reports the total size used by the collection in bytes. Provides a wr
Reports the total size used by the indexes on a collection. Provides
Reports the total size of a collection, including the size of all docum
Modifies a document in a collection.
Performs diagnostic operations on a collection.
db.collection.aggregate()
New in version 2.2.
Definition
db.collection.aggregate(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 484) 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 Additional options that aggregate() (page 22) passes to the
aggregate (page 210) 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 Specifies to return the information on the processing of the pipeline. See
Return Information on Aggregation Pipeline Operation (page 24) for an example.
New in version 2.6.
field boolean allowDiskUse Enables writing to temporary files. When set to true, aggregation
operations can write data to the _tmp subdirectory in the dbPath directory. See Perform
Large Sort Operation with External Sort (page 24) for an example.
New in version 2.6.
field document cursor 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 24) 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.
22
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
If the pipeline includes the $out (page 491) operator, aggregate() (page 22) returns an
empty cursor. See $out (page 491) for more information.
Changed in version 2.6: The db.collection.aggregate() (page 22) 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 22) 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 210) command.
See also:
For more information, see http://docs.mongodb.org/manual/core/aggregation-pipeline, Aggregation Reference (page 564), http://docs.mongodb.org/manual/core/aggregation-pipeline-limits,
and aggregate (page 210).
Cursor Behavior In the mongo (page 610) shell,
if the cursor returned from the
db.collection.aggregate() (page 22) is not assigned to a variable using the var keyword, then the mongo (page 610) shell automatically iterates the cursor up to 20 times.
See
http://docs.mongodb.org/manual/core/cursors for cursor behavior in the mongo (page 610)
shell and http://docs.mongodb.org/manual/tutorial/iterate-a-cursor for handling cursors in
the mongo (page 610) 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:
•
•
•
•
•
•
•
•
cursor.hasNext() (page 87)
cursor.next() (page 93)
cursor.toArray() (page 99)
cursor.forEach() (page 86)
cursor.map() (page 88)
cursor.objsLeftInBatch() (page 93)
cursor.itcount()
cursor.pretty()
Examples The examples in this section use the db.collection.aggregate() (page 22) helper provided in
the 2.6 version of the mongo (page 610) shell.
The following examples use the collection orders that contains the following documents:
{
{
{
{
{
_id:
_id:
_id:
_id:
_id:
1,
2,
3,
4,
5,
cust_id:
cust_id:
cust_id:
cust_id:
cust_id:
"abc1",
"xyz1",
"xyz1",
"xyz1",
"abc1",
ord_date:
ord_date:
ord_date:
ord_date:
ord_date:
ISODate("2012-11-02T17:04:11.102Z"),
ISODate("2013-10-01T17:04:11.102Z"),
ISODate("2013-10-12T17:04:11.102Z"),
ISODate("2013-10-11T17:04:11.102Z"),
ISODate("2013-11-12T17:04:11.102Z"),
status:
status:
status:
status:
status:
"A",
"A",
"D",
"D",
"A",
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:
db.orders.aggregate([
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
])
2.1. mongo Shell Methods
23
amount:
amount:
amount:
amount:
amount:
50 }
100 }
25 }
125 }
25 }
MongoDB Reference Manual, Release 2.8.0-rc3
The operation returns a cursor with the following documents:
{ "_id" : "xyz1", "total" : 100 }
{ "_id" : "abc1", "total" : 75 }
The mongo (page 610) shell iterates the returned cursor automatically to print the results.
See
http://docs.mongodb.org/manual/tutorial/iterate-a-cursor for handling cursors manually in
the mongo (page 610) shell.
Return Information on Aggregation Pipeline Operation The following aggregation operation sets the option
explain to true to return information about the aggregation operation.
db.orders.aggregate(
[
{ $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 610) shell iterates the returned cursor automatically to print the results.
See
http://docs.mongodb.org/manual/tutorial/iterate-a-cursor for handling cursors manually in
the mongo (page 610) 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 = db.stocks.aggregate(
[
{ $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:
1
24
index-filters can affect the choice of index used. See index-filters for details.
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
cursor: { batchSize: <int> }
For example, the following aggregation operation specifies the initial batch size of 0 for the cursor:
db.orders.aggregate(
[
{
{
{
{
$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_MORE2 operations as with other
MongoDB cursors.
The mongo (page 610) shell iterates the returned cursor automatically to print the results.
See
http://docs.mongodb.org/manual/tutorial/iterate-a-cursor for handling cursors manually in
the mongo (page 610) shell.
db.collection.copyTo()
Definition
db.collection.copyTo(newCollection)
Copies all documents from collection into newCollection using server-side JavaScript.
newCollection does not exist, MongoDB creates it.
If
If authorization is enabled, you must have access to all actions on all resources in order to run
db.collection.copyTo() (page 25). Providing such access is not recommended, but if your organization requires a user to run db.collection.copyTo() (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 db.collection.copyTo() (page 25) check field types to ensure that the
operation does not remove type information from documents during the translation from BSON to JSON.
Consider using cloneCollection() (page 101) to maintain type fidelity.
The db.collection.copyTo() (page 25) method uses the eval (page 237) command internally. As
a result, the db.collection.copyTo() (page 25) operation takes a global lock that blocks all other
read and write operations until the db.collection.copyTo() (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 237) internally, the copy operations will block all other
operations on the mongod (page 583) instance.
Example The following operation copies all documents from the source collection into the target collection.
2 http://docs.mongodb.org/meta-driver/latest/legacy/mongodb-wire-protocol/#wire-op-get-more
2.1. mongo Shell Methods
25
MongoDB Reference Manual, Release 2.8.0-rc3
db.source.copyTo(target)
db.collection.count()
Definition
db.collection.count(<query>)
Returns the count of documents that would match a find() (page 36) query.
The
db.collection.count() (page 26) method does not perform the find() (page 36) operation but
instead counts and returns the number of results that match a query.
The db.collection.count() (page 26) method has the following parameter:
param document query The query selection criteria.
The
db.collection.count()
(page
26)
db.collection.find(<query>).count() construct.
See also:
method
is
equivalent
to
the
cursor.count() (page 83)
Behavior
Sharded Clusters On a sharded cluster, db.collection.count() (page 26) 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 486) stage of the
db.collection.aggregate() (page 22) method to $sum (page 554) the documents. For example, the
following operation counts the documents in a collection:
db.collection.aggregate(
[
{ $group: { _id: null, count: { $sum: 1 } } }
]
)
To get a count of documents that match a query condition, include the $match (page 490) stage as well:
db.collection.aggregate(
[
{ $match: <query condition> },
{ $group: { _id: null, count: { $sum: 1 } } }
]
)
See Perform a Count (page 491) 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.
26
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
For example, the following operations can return the count using only the index:
db.collection.find( { a: 5, b: 5 } ).count()
db.collection.find( { a: { $gt: 5 } } ).count()
db.collection.find( { 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.
db.collection.find( { a: 5, b: { $in: [ 1, 2, 3 ] } } ).count()
db.collection.find( { a: { $gt: 5 }, b: 5 } ).count()
db.collection.find( { 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 subsequent 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:
db.orders.count()
This operation is equivalent to the following:
db.orders.find().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’):
db.orders.count( { ord_dt: { $gt: new Date('01/01/2012') } } )
The query is equivalent to the following:
db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).count()
db.collection.createIndex()
Definition
db.collection.createIndex(keys, options)
Deprecated since version 1.8.
Creates indexes on collections.
param document keys For each field to index, a key-value pair with the field and the index order:
1 for ascending or -1 for descending.
param document options One or more key-value pairs that specify index options. For a list of
options, see db.collection.ensureIndex() (page 30).
See also:
http://docs.mongodb.org/manual/indexes, db.collection.createIndex() (page 27),
db.collection.dropIndex() (page 29), db.collection.dropIndexes() (page 30),
db.collection.getIndexes() (page 48), db.collection.reIndex() (page 65), and
db.collection.totalIndexSize() (page 72)
2.1. mongo Shell Methods
27
MongoDB Reference Manual, Release 2.8.0-rc3
db.collection.dataSize()
db.collection.dataSize()
Returns The size of the collection. This method provides a wrapper around the size (page 349)
output of the collStats (page 348) (i.e. db.collection.stats() (page 71)) command.
db.collection.distinct()
Definition
db.collection.distinct(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.
param document query A query that specifies the documents from which to retrieve the distinct
values.
The db.collection.distinct() (page 28) method provides a wrapper around the distinct
(page 215) command. Results must not be larger than the maximum BSON size (page 692).
When possible to use covered indexes, the db.collection.distinct() (page 28) method will use an
index to find the documents in the query as well as to return the data.
Examples The following are examples of the db.collection.distinct() (page 28) method:
• Return an array of the distinct values of the field ord_dt from all documents in the orders collection:
db.orders.distinct( 'ord_dt' )
• Return an array of the distinct values of the field sku in the subdocument item from all documents in the
orders collection:
db.orders.distinct( 'item.sku' )
• Return an array of the distinct values of the field ord_dt from the documents in the orders collection where
the price is greater than 10:
db.orders.distinct( 'ord_dt', { price: { $gt: 10 } } )
db.collection.drop()
Definition
db.collection.drop()
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 335) command.
db.collection.drop() (page 28) has the form:
db.collection.drop()
db.collection.drop() (page 28) takes no arguments and will produce an error if called with any arguments.
Returns
• true when successfully drops a collection.
28
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
• 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.
db.students.drop()
db.collection.dropIndex()
Definition
db.collection.dropIndex(index)
Drops or removes the specified index from a collection. The db.collection.dropIndex() (page 29)
method provides a wrapper around the dropIndexes (page 335) command.
Note: You cannot drop the default index on the _id field.
The db.collection.dropIndex() (page 29) method takes the following parameter:
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. 3
To drop a text index, specify the index name.
To get the index name or the index specification document for the db.collection.dropIndex()
(page 29) method, use the db.collection.getIndexes() (page 48) method.
Example Consider a pets collection. Calling the getIndexes() (page 48) method on the pets collection
returns the following indexes:
[
{
"v" : 1,
"key" : { "_id" : 1 },
"ns" : "test.pets",
"name" : "_id_"
},
{
"v" : 1,
"key" : { "cat" : -1 },
"ns" : "test.pets",
"name" : "catIdx"
},
{
"v" : 1,
"key" : { "cat" : 1, "dog" : -1 },
"ns" : "test.pets",
"name" : "cat_1_dog_-1"
}
]
3 When using a mongo (page 610) 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.
2.1. mongo Shell Methods
29
MongoDB Reference Manual, Release 2.8.0-rc3
The single field index on the field cat has the user-specified name of catIdx 4 and the index specification document
of { "cat" : -1 }.
To drop the index catIdx, you can use either the index name:
db.pets.dropIndex( "catIdx" )
Or you can use the index specification document { "cat" :
-1 }:
db.pets.dropIndex( { "cat" : -1 } )
db.collection.dropIndexes()
db.collection.dropIndexes()
Drops all indexes other than the required index on the _id field. Only call dropIndexes() (page 30) as a
method on a collection object.
db.collection.ensureIndex()
Definition
db.collection.ensureIndex(keys, options)
Creates an index on the specified field if the index does not already exist.
The ensureIndex() (page 30) method has the following fields:
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 index-type-list for more information.
param document options A document that contains a set of options that controls the creation of the
index. See Options (page 30) 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.
Options for All Index Types The following options are available for all index types unless otherwise specified:
param Boolean background 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 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 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.
database.collection) cannot be longer than the Index Name Limit (page 693).
4 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.
30
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
param Boolean dropDups Creates a unique index on a field that may have duplicates. MongoDB indexes only the first occurrence of a key and removes all documents from the collection that contain
subsequent occurrences of that key. Specify true to create unique index. The default value is
false.
The option is unavailable for hashed indexes.
Deprecated since version 2.6.
Warning: dropDups will delete data from your collection when building the index.
param Boolean sparse 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 default
value is false. See http://docs.mongodb.org/manual/core/index-sparse 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 Specifies a value,
in seconds,
as a TTL to
control how long MongoDB retains documents in this collection.
See
http://docs.mongodb.org/manual/tutorial/expire-data for more information
on this functionality. This applies only to TTL indexes.
param index version v The index version number. The default index version depends on the version
of mongod (page 583) 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 New in version 2.8.
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.
Options for text Indexes The following options are available for text indexes only:
param document weights For text indexes,
a document that contains field and
weight pairs.
The weight is an integer ranging from 1 to 99,999 and denotes 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
http://docs.mongodb.org/manual/tutorial/control-results-of-text-search
to adjust the scores. The default value is 1.
param string default_language 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
http://docs.mongodb.org/manual/tutorial/specify-language-for-text-index
for more information and examples. The default value is english.
2.1. mongo Shell Methods
31
MongoDB Reference Manual, Release 2.8.0-rc3
param string language_override For text indexes, the name of the field, in the collection’s 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 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 For 2dsphere indexes, the 2dsphere 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 2d Indexes The following options are available for 2d indexes only:
param integer bits 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 For 2d indexes, the lower inclusive boundary for the longitude and latitude values.
The default value is -180.0.
param number max For 2d indexes, the upper inclusive boundary for the longitude and latitude 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 ensureIndex() (page 30) method has the behaviors described here.
• To add or change index options you must drop the index using the dropIndex() (page 29) method and issue
another ensureIndex() (page 30) operation with the new options.
If you create an index with one set of options, and then issue the ensureIndex() (page 30) method with the
same index fields and different options without first dropping the index, ensureIndex() (page 30) will not
rebuild the existing index with the new options.
• If you call multiple ensureIndex() (page 30) 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.
• MongoDB will not create an index (page 30) 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.
32
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Examples
Create an Ascending Index on a Single Field The following example creates an ascending index on the field
orderDate.
db.collection.ensureIndex( { orderDate: 1 } )
If the keys document specifies more than one field, then ensureIndex() (page 30) 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.)
db.collection.ensureIndex( { 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 95) operations using the index.
See also:
• The http://docs.mongodb.org/manual/indexes section of this manual for full documentation of
indexes and indexing in MongoDB.
• http://docs.mongodb.org/manual/core/index-text for details on creating text indexes.
• index-feature-geospatial and index-geohaystack-index for geospatial queries.
• index-feature-ttl for expiration of data.
• db.collection.getIndexes() (page 48) to view the specifications of existing indexes for a collection.
db.collection.explain()
Description
db.collection.explain()
New in version 2.8.
Returns information on the query plan for the following operations: aggregate() (page 22); count()
(page 26); find() (page 36); group() (page 51); remove() (page 66); and update() (page 72) methods.
To use db.collection.explain() (page 33), append to db.collection.explain() (page 33) the
method(s) available to explain:
db.collection.explain().<method(...)>
For example,
db.products.explain().remove( { category: "apparel" }, { justOne: true } )
For more examples, see Examples (page 35).
For a list of methods available for use with
db.collection.explain() (page 33), see db.collection.explain().help() (page 35).
The db.collection.explain() (page 33) method has the following parameter:
param string verbosity 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".
2.1. mongo Shell Methods
33
MongoDB Reference Manual, Release 2.8.0-rc3
For backwards compatibility with earlier versions of cursor.explain() (page 85), MongoDB interprets true as "allPlansExecution" and false as "queryPlanner".
For more information on the modes, see Verbosity Modes (page 34).
Behavior
Verbosity Modes The behavior of db.collection.explain() (page 33) and the amount of information returned depend on the verbosity mode.
queryPlanner Mode By default, db.collection.explain() (page 33) runs in queryPlanner verbosity mode.
MongoDB runs the query optimizer to choose the winning plan for the operation under evaluation.
db.collection.explain() (page 33) returns the queryPlanner 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, db.collection.explain() (page 33) returns information about the update or delete operations that would be performed, but does not apply the modifications to the database.
db.collection.explain() (page 33) returns the queryPlanner and executionStats information for
the evaluated method. However, executionStats 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, db.collection.explain() (page 33) returns information about the update or delete operations that would be performed, but does not apply the modifications to the database.
db.collection.explain() (page 33) returns the queryPlanner and executionStats information for
the evaluated method. The executionStats includes the completed query execution information for the winning
plan.
If the query optimizer considered more than one plan, executionStats information also includes the partial
execution information captured during the plan selection phase for both the winning and rejected candidate plans.
explain() Mechanics The db.collection.explain() (page 33) method wraps the explain (page 354)
command and is the preferred way to run explain (page 354).
db.collection.explain().find() is similar to db.collection.find().explain() (page 85) with
the following key differences:
• The db.collection.explain().find() construct allows for the additional chaining of query modifiers. For list of query modifiers, see db.collection.explain().find().help() (page 35).
• The db.collection.explain().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 610) shell,
the mongo (page 610) 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
db.collection.explain().find().help() (page 35).
34
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.collection.explain().aggregate() is equivalent to passing the explain (page 24) option to the
db.collection.aggregate() (page 22) method.
help() To see the list of operations supported by db.collection.explain() (page 33), run:
db.collection.explain().help()
db.collection.explain().find() returns a cursor, which allows for the chaining of query modifiers. To
see the list of query modifiers supported by db.collection.explain().find() (page 33) as well as cursorrelated methods, run:
db.collection.explain().find().help()
You can chain multiple modifiers to db.collection.explain().find(). For an example, see Explain find()
with Modifiers (page 35).
Examples
queryPlanner Mode By default, db.collection.explain() (page 33) runs in "queryPlanner" verbosity mode.
The following example runs db.collection.explain() (page 33) in “queryPlanner” (page 34) verbosity
mode to return the query planning information for the specified count() (page 26) operation:
db.products.explain().count( { quantity: { $gt: 50 } } )
executionStats Mode The following example runs db.collection.explain() (page 33) in “executionStats” (page 34) verbosity mode to return the query planning and execution information for the specified find()
(page 36) operation:
db.products.explain("executionStats").find(
{ quantity: { $gt: 50 }, category: "apparel" }
)
allPlansExecution Mode The following example runs db.collection.explain() (page 33) in
“allPlansExecution” (page 34) verbosity mode. The db.collection.explain() (page 33) returns the
queryPlanner and executionStats for all considered plans for the specified update() (page 72) 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.
db.products.explain("allPlansExecution").update(
{ quantity: { $lt: 1000}, category: "apparel" },
{ $set: { reorder: true } }
)
Explain find() with Modifiers db.collection.explain().find() construct allows for the chaining of
query modifiers. For example, the following operation provides information on the find() (page 36) method with
sort() (page 95) and hint() (page 87) query modifiers.
2.1. mongo Shell Methods
35
MongoDB Reference Manual, Release 2.8.0-rc3
db.products.explain("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 610) shell:
db.collection.explain().find().help()
Iterate the explain().find() Return Cursor db.collection.explain().find() returns a cursor
to the explain results. If run interactively in the mongo (page 610) shell, the mongo (page 610) 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:
var explainResult = db.products.explain().find( { category: "apparel" } ).next();
Output db.collection.explain() (page 33) operations can return information regarding:
• queryPlanner, which details the plan selected by the query optimizer and lists the rejected plans;
• executionStats, which details the execution of the winning plan and the rejected plans; and
• serverInfo, which provides information on the MongoDB instance.
The verbosity mode (i.e. queryPlanner, executionStats, allPlansExecution) determines whether the
results include executionStats and whether executionStats includes data captured during plan selection.
For details on the output, see http://docs.mongodb.org/manual/reference/explain-results.
For a mixed version sharded cluster with version 2.8 mongos (page 601) and at least one 2.6 mongod (page 583)
shard, when you run db.collection.explain() (page 33) in a version 2.8 mongo (page 610) shell,
db.collection.explain() (page 33) will retry with the $explain (page 556) operator to return results in
the 2.6 format.
db.collection.find()
Definition
db.collection.find(<criteria>, <projection>)
Selects documents in a collection and returns a cursor to the selected documents.
5
param document criteria Specifies selection criteria using query operators (page 400). To return
all documents in a collection, omit this parameter or pass an empty document ({}).
param document projection Specifies the fields to return using projection operators (page 444).
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 36) method
“returns documents,” the method is actually returning a cursor to the documents.
If the projection argument is specified, the matching documents contain only the
projection fields and the _id field. You can optionally exclude the _id field.
Executing find() (page 36) directly in the mongo (page 610) shell automatically iterates the
cursor to display up to the first 20 documents. Type it to continue iteration.
5
36
db.collection.find() (page 36) is a wrapper for the more formal query structure that uses the $query (page 560) operator.
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
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 36) 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.
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 36) 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:
db.bios.find()
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:
db.products.find( { qty: { $gt: 25 } } )
Query for Equality The following operation returns documents in the bios collection where _id equals 5:
db.bios.find( { _id: 5 } )
Query Using Operators The following operation returns documents in the bios collection where _id equals
either 5 or ObjectId("507c35dd8fada716c89d0013"):
db.bios.find(
{
_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:
db.collection.find( { field: { $gt: value1, $lt: value2 } } );
2.1. mongo Shell Methods
37
MongoDB Reference Manual, Release 2.8.0-rc3
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:
db.students.find( { score: { $gt: 0, $lt: 2 } } )
Matches the following documents:
{ "_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":
db.bios.find( { contribs: "UNIX" } )
Query an Array of Documents The following operation returns documents in the bios collection where
awards array contains a subdocument element that contains the award field equal to "Turing Award" and the
year field greater than 1980:
db.bios.find(
{
awards: {
$elemMatch: {
award: "Turing Award",
year: { $gt: 1980 }
}
}
}
)
Query Subdocuments
Query Exact Matches on Subdocuments The following operation returns documents in the bios collection
where the subdocument name is exactly { first: "Yukihiro", last: "Matsumoto" }, including the
order:
38
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.bios.find(
{
name: {
first: "Yukihiro",
last: "Matsumoto"
}
}
)
The name field must match the sub-document exactly. The query does not match documents with the following name
fields:
{
first: "Yukihiro",
aka: "Matz",
last: "Matsumoto"
}
{
last: "Matsumoto",
first: "Yukihiro"
}
Query Fields of a Subdocument The following operation returns documents in the bios collection where
the subdocument 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 a subdocument:
db.bios.find(
{
"name.first": "Yukihiro",
"name.last": "Matsumoto"
}
)
The query matches the document where the name field contains a subdocument 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:
2.1. mongo Shell Methods
39
MongoDB Reference Manual, Release 2.8.0-rc3
db.products.find( { 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:
db.bios.find( { }, { 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 subdocument and the birth field:
db.bios.find(
{ contribs: 'OOP' },
{ 'name.first': 0, birth: 0 }
)
Explicitly Exclude the _id Field The following operation excludes the _id and qty fields from the result set:
db.products.find( { 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:
db.bios.find(
{ },
{ name: 1, contribs: 1, _id: 0 }
)
On Arrays and Subdocuments The following operation queries the bios collection and returns the last
field in the name subdocument and the first two elements in the contribs array:
db.bios.find(
{ },
{
_id: 0,
'name.last': 1,
contribs: { $slice: 2 }
}
)
Iterate the Returned Cursor The find() (page 36) method returns a cursor to the results. In the mongo
(page 610) shell, if the returned cursor is not assigned to a variable using the var keyword, the cursor is automatically iterated up to 20 times to access up to the first 20 documents that match the query. You can use the
DBQuery.shellBatchSize to change the number of iterations. See Flags (page 82) and cursor-behaviors. To
iterate manually, assign the returned cursor to a variable using the var keyword.
40
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
With Variable Name The following example uses the variable myCursor to iterate over the cursor and print the
matching documents:
var myCursor = db.bios.find( );
myCursor
With next() Method The following example uses the cursor method next() (page 93) to access the documents:
var myCursor = db.bios.find( );
var myDocument = myCursor.hasNext() ? myCursor.next() : null;
if (myDocument) {
var myName = myDocument.name;
print (tojson(myName));
}
To print, you can also use the printjson() method instead of print(tojson()):
if (myDocument) {
var myName = myDocument.name;
printjson(myName);
}
With forEach() Method The following example uses the cursor method forEach() (page 86) to iterate the
cursor and access the documents:
var myCursor = db.bios.find( );
myCursor.forEach(printjson);
Modify the Cursor Behavior The mongo (page 610) shell and the drivers provide several cursor methods that
call on the cursor returned by the find() (page 36) method to modify its behavior.
Order Documents in the Result Set The sort() (page 95) 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:
db.bios.find().sort( { name: 1 } )
sort() (page 95) corresponds to the ORDER BY statement in SQL.
Limit the Number of Documents to Return The limit() (page 88) method limits the number of documents in
the result set. The following operation returns at most 5 documents in the bios collection:
db.bios.find().limit( 5 )
limit() (page 88) corresponds to the LIMIT statement in SQL.
Set the Starting Point of the Result Set The skip() (page 94) 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:
2.1. mongo Shell Methods
41
MongoDB Reference Manual, Release 2.8.0-rc3
db.bios.find().skip( 5 )
Combine Cursor Methods The following example chains cursor methods:
db.bios.find().sort( { name: 1 } ).limit( 5 )
db.bios.find().limit( 5 ).sort( { name: 1 } )
Regardless of the order you chain the limit() (page 88) and the sort() (page 95), the request to the server has
the structure that treats the query and the sort() (page 95) modifier as a single object. Therefore, the limit()
(page 88) operation method is always applied after the sort() (page 95) regardless of the specified order of the
operations in the chain. See the meta query operators (page 555).
db.collection.findAndModify()
Definition
db.collection.findAndModify(<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 42) method is a shell helper around the findAndModify (page 239) command.
The findAndModify() (page 42) method has the following form:
db.collection.findAndModify({
query: <document>,
sort: <document>,
remove: <boolean>,
update: <document>,
new: <boolean>,
fields: <document>,
upsert: <boolean>
});
The db.collection.findAndModify() (page 42) method takes a document parameter with the following subdocument fields:
param document query The selection criteria for the modification. The query field employs the
same query selectors (page 400) as used in the db.collection.find() (page 36) method.
Although the query may match multiple documents, findAndModify() (page 42) will only
select one document to modify.
param document sort Determines which document the operation modifies if the query selects multiple documents. findAndModify() (page 42) 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 document 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 update of the selected document. The update field employs the same update operators (page 451)
or field: value specifications to modify the selected document.
param Boolean new When true, returns the modified document rather than the original. The
findAndModify() (page 42) method ignores the new option for remove operations. The
default is false.
42
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
param document fields 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 Used in conjunction with the update field.
When true, findAndModify() (page 42) creates a new document if no document matches
the query, or if documents match the query, findAndModify() (page 42) performs an
update. To avoid multiple upserts, ensure that the query fields are uniquely indexed.
The default is false.
Return Data The findAndModify() (page 42) method returns either: the pre-modification document or, if
new: true is set, the modified document.
Note:
• If the query finds no document for update or remove operations, findAndModify() (page 42) returns
null.
• If the query finds no document for an update with an upsert operation, findAndModify() (page 42)
creates a new document. If new is false, and the sort option is NOT specified, the method returns null.
• If the query finds no document for an update with an upsert operation, findAndModify() (page 42)
creates a new document. If new is false, and a sort option, the method returns an empty document {}.
Behavior
Upsert and Unique Index When findAndModify() (page 42) 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:
db.people.findAndModify({
query: { name: "Andy" },
sort: { rating: 1 },
update: { $inc: { score: 1 } },
upsert: true
})
Then, if these clients’ findAndModify() (page 42) 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 42) successfully inserts a new document.
• Zero or more findAndModify() (page 42) methods update the newly inserted document.
• Zero or more findAndModify() (page 42) 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.
2.1. mongo Shell Methods
43
MongoDB Reference Manual, Release 2.8.0-rc3
Sharded Collections When using findAndModify (page 239) in a sharded environment, the query must contain the shard key for all operations against the shard cluster for the sharded collections.
findAndModify (page 239) operations issued against mongos (page 601) instances for non-sharded collections
function normally.
Comparisons with the update Method When updating a document, findAndModify() (page 42) and the
update() (page 72) method operate differently:
• By default, both operations modify a single document. However, the update() (page 72) method with its
multi option can modify more than one document.
• If multiple documents match the update criteria, for findAndModify() (page 42), you can specify a sort
to provide some measure of control on which document to update.
With the default behavior of the update() (page 72) method, you cannot specify which single document to
update when multiple documents match.
• By default, findAndModify() (page 42) method returns the pre-modified version of the document. To obtain
the updated document, use the new option.
The update() (page 72) method returns a WriteResult (page 201) object that contains the status of the
operation. To return the updated document, use the find() (page 36) 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 42) to override the default write concern whereas, starting in MongoDB 2.6, you can specify a write concern to the update() (page 72) method.
When
modifying
a
single
document,
both
findAndModify()
(page
42)
and
the
update()
(page
72)
method
atomically
update
the
document.
See
http://docs.mongodb.org/manual/core/write-operations-atomicity 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:
db.people.findAndModify({
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:
44
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
{
"_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:
null
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:
db.people.findAndModify({
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 option. 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:
db.people.findAndModify({
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"
}
2.1. mongo Shell Methods
45
MongoDB Reference Manual, Release 2.8.0-rc3
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:
db.people.findAndModify(
{
query: { state: "active" },
sort: { rating: 1 },
remove: true
}
)
The method returns the deleted document:
{
"_id" : ObjectId("52fba867ab5fdca1299674ad"),
"name" : "XYZ123",
"score" : 1,
"state" : "active",
"rating" : 3
}
db.collection.findOne()
Definition
db.collection.findOne(<criteria>, <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.
param document criteria Specifies query selection criteria using query operators (page 400).
param document projection Specifies the fields to return using projection operators (page 444).
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 46) 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 46) returns a document
that only contains the projection fields. The _id field is always included unless you
explicitly exclude it.
Although similar to the find() (page 36) method, the findOne() (page 46) method
returns a document rather than a cursor.
Examples
46
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
With Empty Query Specification The following operation returns a single document from the bios
collection:
db.bios.findOne()
With a Query Specification The following operation returns the first matching document from the bios
collection where either the field first in the subdocument name starts with the letter G or where the field
birth is less than new Date(’01/01/1945’):
db.bios.findOne(
{
$or: [
{ 'name.first' : /^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:
db.bios.findOne(
{ },
{ 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 subdocument, and the birth field:
db.bios.findOne(
{ contribs: 'OOP' },
{ _id: 0, 'name.first': 0, birth: 0 }
)
The findOne Result Document You cannot apply cursor methods to the result of findOne() (page 46) because
a single document is returned. You have access to the document directly:
var myDocument = db.bios.findOne();
if (myDocument) {
var myName = myDocument.name;
print (tojson(myName));
}
db.collection.getIndexStats()
Definition
2.1. mongo Shell Methods
47
MongoDB Reference Manual, Release 2.8.0-rc3
db.collection.getIndexStats(index)
Displays a human-readable summary of aggregated statistics about an index’s B-tree data structure. The information summarizes the output returned by the indexStats (page 360) command and indexStats()
(page 54) method. The getIndexStats() (page 47) method displays the information on the screen and does
not return an object.
The getIndexStats() (page 47) method has the following form:
db.<collection>.getIndexStats( { index : "<index name>" } )
param document index The index name.
The getIndexStats() (page 47) method is available only when connected to a mongod (page 583) instance
that uses the --enableExperimentalIndexStatsCmd option.
To view index names for a collection, use the getIndexes() (page 48) method.
Warning: Do not use getIndexStats() (page 47) or indexStats (page 360) with production
deployments.
Example The following command returns information for an index named type_1_traits_1:
db.animals.getIndexStats({index:"type_1_traits_1"})
The command returns the following summary. For more information on the B-tree statistics, see indexStats
(page 360).
-- index "undefined" -version 1 | key pattern { "type" : 1,
2 deep, bucket body is 8154 bytes
"traits" : 1 } | storage namespace "test.animals.$type_1_tr
bucket count
45513
on average 99.401 % (В±0.463 %) full
49.581 % (В±4.135 %) bson keys,
-- depth 0 -bucket count
1
on average 71.511 % (В±0.000 %) full
36.191 % (В±0.000 %) bson keys,
-- depth 1 -bucket count
180
on average 98.954 % (В±5.874 %) full
49.732 % (В±5.072 %) bson keys,
-- depth 2 -bucket count
45332
on average 99.403 % (В±0.245 %) full
49.580 % (В±4.130 %) bson keys,
db.collection.getIndexes()
Definition
db.collection.getIndexes()
Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
You must call the db.collection.getIndexes() (page 48) on a collection. For example:
db.collection.getIndexes()
Change collection to the name of the collection whose indexes you want to learn.
48
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Considerations Changed in version 2.8.0.
If you use db.collection.getIndexes() (page 48) from a version of the mongo (page 610) shell before 2.8.0,
on a mongod (page 583) instance that uses the��wiredTiger�� storage engine, db.collection.getIndexes()
(page 48) will return no data, even if there are existing indexes.
Output The db.collection.getIndexes() (page 48) items consist of the following fields:
system.indexes.v
Holds the version of the index.
The index version depends on the version of mongod (page 583) that created the index. Before version 2.0 of
MongoDB, the this value was 0; versions 2.0 and later use version 1.
system.indexes.key
Contains a document holding the keys held in the index, and the order of the index. Indexes may be either
descending or ascending order. A value of negative one (e.g. -1) indicates an index sorted in descending order
while a positive value (e.g. 1) indicates an index sorted in an ascending order.
system.indexes.ns
The namespace context for the index.
system.indexes.name
A unique name for the index comprised of the field names and orders of all keys.
db.collection.getShardDistribution()
Definition
db.collection.getShardDistribution()
Returns
Prints the data distribution statistics for a sharded collection.
You must call the
getShardDistribution() (page 49) method on a sharded collection, as in the following example:
db.myShardedCollection.getShardDistribution()
In the following example, the collection has two shards. The output displays both the individual shard distribution 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 : <stats.size> docs : <stats.count> 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:
http://docs.mongodb.org/manual/sharding
2.1. mongo Shell Methods
49
MongoDB Reference Manual, Release 2.8.0-rc3
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.
• <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 documents per chunk for the shard.
• <stats.size> is a value that reports the total size of the data in the sharded collection, including the unit of
measure.
• <stats.count> 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 example:
<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 collection’s total data size, for example:
<estDataPercent-x> = <size-x>/<stats.size>
• <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>/<stats.count>
• stats.shards[ <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/MyMachine.local:30000,MyMachine.local:30001,MyMachine.local:30002
data : 38.14Mb docs : 1000003 chunks : 2
estimated data per chunk : 19.07Mb
estimated docs per chunk : 500001
Shard shard-b at shard-b/MyMachine.local:30100,MyMachine.local:30101,MyMachine.local:30102
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
50
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.collection.getShardVersion()
db.collection.getShardVersion()
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.
db.collection.group()
Recommended Alternatives
Because db.collection.group() (page 51) uses JavaScript, it is subject to a number of performance limitations. For most cases the $group (page 486) operator in the aggregation pipeline provides a suitable
alternative with fewer restrictions.
Definition
db.collection.group({ 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 51) method returns an array.
The db.collection.group() (page 51) 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 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 process. If you omit the cond field, db.collection.group() (page 51) processes all the
documents in the collection for the group operation.
field function finalize A function that runs each item in the result set before
db.collection.group() (page 51) returns the final value. This function can either
modify the result document or replace the result document as a whole.
The db.collection.group() (page 51) method is a shell wrapper for the group (page 216) command.
However, the db.collection.group() (page 51) method takes the keyf field and the reduce field
whereas the group (page 216) command takes the $keyf field and the $reduce field.
Behavior
Limits and Restrictions The db.collection.group() (page 51) 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 692).
2.1. mongo Shell Methods
51
MongoDB Reference Manual, Release 2.8.0-rc3
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 220). Previous versions had
a limit of 10,000 elements.
Prior to 2.4, the db.collection.group() (page 51) method took the mongod (page 583) instance’s 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 220), the group (page 216) command, and $where (page 421) operator expressions cannot
access certain global functions or properties, such as db, that are available in the mongo (page 610) shell.
When upgrading to MongoDB 2.4, you will need to refactor your code if your map-reduce operations
(page 220), group (page 216) commands, or $where (page 421) 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 220), the
group (page 216) command, and $where (page 421) operator expressions in MongoDB 2.4:
Available Properties
Available Functions
args
MaxKey
MinKey
assert()
BinData()
DBPointer()
DBRef()
doassert()
emit()
gc()
HexData()
hex_md5()
isNumber()
isObject()
ISODate()
isString()
Map()
MD5()
NumberInt()
NumberLong()
ObjectId()
print()
printjson()
printjsononeline()
sleep()
Timestamp()
tojson()
tojsononeline()
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-01T04:00:00Z"),
ship_dt: ISODate("2012-07-02T04:00:00Z"),
item: { sku: "abc123",
price: 1.99,
uom: "pcs",
qty: 25 }
}
Group by Two Fields The following example groups by the ord_dt and item.sku fields those documents that
have ord_dt greater than 01/01/2011:
52
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.orders.group(
{
key: { ord_dt: 1, 'item.sku': 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"
"ord_dt"
"ord_dt"
"ord_dt"
"ord_dt"
"ord_dt"
"ord_dt"
"ord_dt"
"ord_dt"
"ord_dt"
"ord_dt"
:
:
:
:
:
:
:
:
:
:
:
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-06-01T04:00:00Z"),
ISODate("2012-06-01T04:00:00Z"),
ISODate("2012-06-01T04:00:00Z"),
ISODate("2012-05-01T04:00:00Z"),
ISODate("2012-05-01T04:00:00Z"),
ISODate("2012-06-08T04:00:00Z"),
ISODate("2012-06-08T04:00:00Z"),
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
:
:
:
:
:
:
:
:
:
:
:
"abc123"},
"abc456"},
"bcd123"},
"efg456"},
"abc123"},
"efg456"},
"ijk123"},
"abc123"},
"abc456"},
"abc123"},
"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 item.sku fields, those documents that
have ord_dt greater than 01/01/2011 and calculates the sum of the qty field for each grouping:
db.orders.group(
{
key: { ord_dt: 1, 'item.sku': 1 },
cond: { ord_dt: { $gt: new Date( '01/01/2012' ) } },
reduce: function( curr, result ) {
result.total += curr.item.qty;
},
initial: { total : 0 }
}
)
The result is an array of documents that contain the group by fields and the calculated aggregation field:
[ {
{
{
{
{
{
{
{
{
"ord_dt"
"ord_dt"
"ord_dt"
"ord_dt"
"ord_dt"
"ord_dt"
"ord_dt"
"ord_dt"
"ord_dt"
:
:
:
:
:
:
:
:
:
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-06-01T04:00:00Z"),
ISODate("2012-06-01T04:00:00Z"),
ISODate("2012-06-01T04:00:00Z"),
ISODate("2012-05-01T04:00:00Z"),
ISODate("2012-05-01T04:00:00Z"),
2.1. mongo Shell Methods
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
:
:
:
:
:
:
:
:
:
"abc123",
"abc456",
"bcd123",
"efg456",
"abc123",
"efg456",
"ijk123",
"abc123",
"abc456",
"total"
"total"
"total"
"total"
"total"
"total"
"total"
"total"
"total"
:
:
:
:
:
:
:
:
:
25
25
10
10
25
15
20
45
25
},
},
},
},
},
},
},
},
},
53
MongoDB Reference Manual, Release 2.8.0-rc3
{ "ord_dt" : ISODate("2012-06-08T04:00:00Z"), "item.sku" : "abc123", "total" : 25 },
{ "ord_dt" : ISODate("2012-06-08T04:00:00Z"), "item.sku" : "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:
db.orders.group(
{
keyf: function(doc) {
return { day_of_week: doc.ord_dt.getDay() };
},
cond: { ord_dt: { $gt: new Date( '01/01/2012' ) } },
reduce: function( curr, result ) {
result.total += curr.item.qty;
result.count++;
},
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];
result.avg = Math.round(result.total / result.count);
}
}
)
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:
http://docs.mongodb.org/manual/core/aggregation
db.collection.indexStats()
Definition
db.collection.indexStats(index)
Aggregates statistics for the B-tree data structure that stores data for a MongoDB index.
The
indexStats() (page 54) method is a thin wrapper around the indexStats (page 360) command. The
indexStats() (page 54) method is available only on mongod (page 583) instances running with the
--enableExperimentalIndexStatsCmd option.
54
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Important: The indexStats() (page 54) method is not intended for production deployments.
The indexStats() (page 54) method has the following form:
db.<collection>.indexStats( { index: "<index name>" } )
The indexStats() (page 54) method has the following parameter:
param document index The index name.
The method takes a read lock and pages into memory all the extents, or B-tree buckets, encountered. The
method might be slow for large indexes if the underlying extents are not already in physical memory. Do not
run indexStats() (page 54) on a replica set primary. When run on a secondary, the command causes the
secondary to fall behind on replication.
The method aggregates statistics for the entire B-tree and for each individual level of the B-tree. For a description
of the command’s output, see indexStats (page 360).
For more information about running indexStats() (page 54), see https://github.com/10gen-labs/storageviz#readme.
db.collection.insert()
Definition
db.collection.insert()
Inserts a document or documents into a collection.
The insert() (page 55) method has the following syntax:
Changed in version 2.6.
db.collection.insert(
<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 A document expressing the write concern. Omit to use the
default write concern. See Safe Writes (page 56).
New in version 2.6.
param boolean ordered 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 55) returns an object that contains the status of the operation.
Returns
2.1. mongo Shell Methods
55
MongoDB Reference Manual, Release 2.8.0-rc3
• A WriteResult (page 57) object for single inserts.
• A BulkWriteResult (page 58) object for bulk inserts.
Behaviors
Safe Writes Changed in version 2.6.
The insert() (page 55) method uses the insert (page 247) 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 55) 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
http://docs.mongodb.org/manual/reference/object-id for the document before inserting. Most
drivers create an ObjectId and insert the _id field, but the mongod (page 583) 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 55) method creates the collection.
Insert a Document without Specifying an _id Field In the following example, the document passed to the
insert() (page 55) method does not contain the _id field:
db.products.insert( { item: "card", qty: 15 } )
During the insert, mongod (page 583) will create the _id field and assign it a unique
http://docs.mongodb.org/manual/reference/object-id 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.
Insert a Document Specifying an _id Field In the following example, the document passed to the insert()
(page 55) method includes the _id field. The value of _id must be unique within the collection to avoid duplicate
key error.
db.products.insert( { _id: 10, item: "box", qty: 20 } )
The operation inserts the following document in the products collection:
{ "_id" : 10, "item" : "box", "qty" : 20 }
56
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Insert Multiple Documents The following example performs a bulk insert of three documents by passing an array
of documents to the insert() (page 55) 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 583)
will create the _id field for the second and third documents during the insert:
db.products.insert(
[
{ _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.
db.products.insert(
[
{ _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 replica set members or the method times out after 5 seconds.
db.products.insert(
{ item: "envelopes", qty : 100, type: "Clasp" },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)
WriteResult Changed in version 2.6.
When passed a single document, insert() (page 55) returns a WriteResult object.
Successful Results The insert() (page 55) returns a WriteResult (page 201) object that contains the status of
the operation. Upon success, the WriteResult (page 201) object contains information on the number of documents
inserted:
WriteResult({ "nInserted" : 1 })
2.1. mongo Shell Methods
57
MongoDB Reference Manual, Release 2.8.0-rc3
Write Concern Errors If the insert() (page 55) method encounters write concern errors, the results include the
WriteResult.writeConcernError (page 201) 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 55) method encounters a non-write concern error, the
results include the WriteResult.writeError (page 201) field:
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.foo.$_i
}
})
BulkWriteResult Changed in version 2.6.
When passed an array of documents, insert() (page 55) returns a BulkWriteResult() (page 198) object. See
BulkWriteResult() (page 198) for details.
db.collection.isCapped()
db.collection.isCapped()
Returns Returns true if the collection is a capped collection, otherwise returns false.
See also:
http://docs.mongodb.org/manual/core/capped-collections
db.collection.mapReduce()
db.collection.mapReduce(map, reduce, {<out>, <query>, <sort>, <limit>, <finalize>, <scope>,
<jsMode>, <verbose>})
The db.collection.mapReduce() (page 58) method provides a wrapper around the mapReduce
(page 220) command.
db.collection.mapReduce(
<map>,
<reduce>,
{
out: <collection>,
query: <document>,
sort: <document>,
limit: <number>,
finalize: <function>,
scope: <document>,
jsMode: <boolean>,
58
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
verbose: <boolean>
}
)
db.collection.mapReduce() (page 58) takes the following parameters:
field Javascript 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 60) for more information.
field JavaScript 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 61) for more information.
field document options A
document
that
specifies
db.collection.mapReduce() (page 58).
additional
parameters
to
The following table describes additional arguments that db.collection.mapReduce() (page 58) 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 62) for more information.
field document query Specifies the selection criteria using query operators (page 400) for determining 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 Javascript function finalize Follows the reduce method and modifies the output.
See Requirements for the finalize Function (page 63) 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:
• 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 storage. 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.
2.1. mongo Shell Methods
59
MongoDB Reference Manual, Release 2.8.0-rc3
• You can only use jsMode for result sets with fewer than 500,000 distinct key arguments
to the mapper’s emit() function.
The jsMode defaults to false.
field Boolean verbose Specifies whether to include the timing information in the result information. The verbose defaults to true to include the timing information.
Note: Changed in version 2.4.
In MongoDB 2.4, map-reduce operations (page 220), the group (page 216) command, and $where
(page 421) operator expressions cannot access certain global functions or properties, such as db, that are available in the mongo (page 610) shell.
When upgrading to MongoDB 2.4, you will need to refactor your code if your map-reduce operations
(page 220), group (page 216) commands, or $where (page 421) 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 220),
the group (page 216) command, and $where (page 421) operator expressions in MongoDB 2.4:
Available Properties
Available Functions
args
MaxKey
MinKey
assert()
BinData()
DBPointer()
DBRef()
doassert()
emit()
gc()
HexData()
hex_md5()
isNumber()
isObject()
ISODate()
isString()
Map()
MD5()
NumberInt()
NumberLong()
ObjectId()
print()
printjson()
printjsononeline()
sleep()
Timestamp()
tojson()
tojsononeline()
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:
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.)
60
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
• A single emit can only hold half of MongoDB’s maximum BSON document size (page 692).
• 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
document’s status field:
function() {
if (this.status == '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 document’s items field:
function() {
this.items.forEach(function(item){ emit(item.sku, 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 MongoDB’s maximum BSON document size (page 692).
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:
• 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:
2.1. mongo Shell Methods
61
MongoDB Reference Manual, Release 2.8.0-rc3
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> exists.
– 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.
• 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.
62
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
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 692).
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 documents 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.
var mapFunction1 = function() {
emit(this.cust_id, this.price);
};
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 Array.sum(valuesPrices);
};
2.1. mongo Shell Methods
63
MongoDB Reference Manual, Release 2.8.0-rc3
3. Perform the map-reduce on all documents in the orders collection using the mapFunction1 map function
and the reduceFunction1 reduce function.
db.orders.mapReduce(
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 results 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 item.sku 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 < this.items.length; idx++) {
var key = this.items[idx].sku;
var value = {
count: 1,
qty: this.items[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.
• In reducedVal, the count field contains the sum of the count fields from the individual array elements, 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 < countObjVals.length; idx++) {
reducedVal.count += countObjVals[idx].count;
reducedVal.qty += countObjVals[idx].qty;
}
return reducedVal;
};
64
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
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) {
reducedVal.avg = reducedVal.qty/reducedVal.count;
return reducedVal;
};
4. Perform the map-reduce operation on the orders collection
reduceFunction2, and finalizeFunction2 functions.
using
the
mapFunction2,
db.orders.mapReduce( 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 db.collection.mapReduce() (page 58) method is identical to that of the
mapReduce (page 220) command. See the Output (page 227) section of the mapReduce (page 220) command
for information on the db.collection.mapReduce() (page 58) output.
Additional Information
• http://docs.mongodb.org/manual/tutorial/troubleshoot-map-function
• http://docs.mongodb.org/manual/tutorial/troubleshoot-reduce-function
• mapReduce (page 220) command
• http://docs.mongodb.org/manual/core/aggregation
• Map-Reduce
• http://docs.mongodb.org/manual/tutorial/perform-incremental-map-reduce
db.collection.reIndex()
db.collection.reIndex()
The db.collection.reIndex() (page 65) 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:
db.collection.reIndex()
2.1. mongo Shell Methods
65
MongoDB Reference Manual, Release 2.8.0-rc3
Normally, MongoDB compacts indexes during routine updates.
For most users, the
db.collection.reIndex() (page 65) 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, db.collection.reIndex() (page 65) will not propagate from the primary to secondaries. db.collection.reIndex() (page 65) will only affect a single mongod (page 583) instance.
Important: db.collection.reIndex() (page 65) will rebuild indexes in the background if the index was
originally specified with this option. However, db.collection.reIndex() (page 65) will rebuild the _id
index in the foreground, which takes the database’s 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 322) and repairDatabase
(page 341) commands as well as the db.collection.reIndex() (page 65) 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 341) command, from continuing with the remainder of the process.
See
http://docs.mongodb.org/manual/core/index-creation for more information on the behavior of
indexing operations in MongoDB.
db.collection.remove()
Definition
db.collection.remove()
Removes documents from a collection.
The db.collection.remove() (page 66) method can have one of two syntaxes. The remove()
(page 66) method can take a query document and an optional justOne boolean:
db.collection.remove(
<query>,
<justOne>
)
Or the method can take a query document and an optional remove options document:
New in version 2.6.
db.collection.remove(
<query>,
{
justOne: <boolean>,
writeConcern: <document>
}
)
param document query Specifies deletion criteria using query operators (page 400). To delete all
documents in a collection, pass an empty document ({}).
66
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Changed in version 2.6: In previous versions, the method invoked with no query parameter
deleted all documents in a collection.
param boolean justOne 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 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 remove() (page 66) returns an object that contains the status of the operation.
Returns A WriteResult (page 68) object that contains the status of the operation.
Behavior
Safe Writes Changed in version 2.6.
The remove() (page 66) method uses the delete (page 234) 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 66) 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 46) 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 482) 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 68) for an example.
Capped Collections You cannot use the remove() (page 66) method with a capped collection.
Sharded Collections All remove() (page 66) 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 66) 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 66) method.
Remove All Documents from a Collection To remove all documents in a collection, call the remove (page 66)
method with an empty query document {}. The following operation deletes all documents from the bios
collection:
db.bios.remove( { } )
This operation is not equivalent to the drop() (page 28) method.
To remove all documents from a collection, it may be more efficient to use the drop() (page 28) method to drop the
entire collection, including the indexes, and then recreate the collection and rebuild the indexes.
2.1. mongo Shell Methods
67
MongoDB Reference Manual, Release 2.8.0-rc3
Remove All Documents that Match a Condition To remove the documents that match a deletion criteria, call the
remove() (page 66) method with the <query> parameter:
The following operation removes all the documents from the collection products where qty is greater than 20:
db.products.remove( { 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 replica
set members or the method times out after 5 seconds.
db.products.remove(
{ 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 66) 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:
db.products.remove( { qty: { $gt: 20 } }, true )
Isolate Remove Operations To isolate the query, include $isolated:
following examples:
1 in the <query> parameter as in the
db.products.remove( { qty: { $gt: 20 }, $isolated: 1 } )
WriteResult Changed in version 2.6.
Successful Results The remove() (page 66) returns a WriteResult (page 201) object that contains the status of
the operation. Upon success, the WriteResult (page 201) object contains information on the number of documents
removed:
WriteResult({ "nRemoved" : 4 })
See also:
WriteResult.nRemoved (page 201)
Write Concern Errors If the remove() (page 66) method encounters write concern errors, the results include the
WriteResult.writeConcernError (page 201) field:
WriteResult({
"nRemoved" : 21,
"writeConcernError" : {
"code" : 64,
"errInfo" : {
"wtimeout" : true
},
"errmsg" : "waiting for replication timed out"
}
})
68
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
See also:
WriteResult.hasWriteConcernError() (page 202)
Errors Unrelated to Write Concern If the remove() (page 66) method encounters a non-write concern error, the
results include WriteResult.writeError (page 201) field:
WriteResult({
"nRemoved" : 0,
"writeError" : {
"code" : 2,
"errmsg" : "unknown top level operator: $invalidFieldName"
}
})
See also:
WriteResult.hasWriteError() (page 202)
db.collection.renameCollection()
Definition
db.collection.renameCollection(target, dropTarget)
Renames a collection. Provides a wrapper for the renameCollection (page 340) database command.
param string target The new name of the collection. Enclose the string in quotes.
param boolean dropTarget If true,
mongod (page 583) drops
renameCollection (page 340) prior to renaming the collection.
the
target
of
Example Call the db.collection.renameCollection() (page 69) method on a collection object. For
example:
db.rrecord.renameCollection("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:
• db.collection.renameCollection() (page 69) cannot move a collection between databases. Use
renameCollection (page 340) for these rename operations.
• db.collection.renameCollection() (page 69) is not supported on sharded collections.
The db.collection.renameCollection() (page 69) method operates within a collection by changing the
metadata associated with a given collection.
Refer to the documentation renameCollection (page 340) for additional warnings and messages.
Warning: The db.collection.renameCollection() (page 69) method and renameCollection
(page 340) command will invalidate open cursors which interrupts queries that are currently returning data.
2.1. mongo Shell Methods
69
MongoDB Reference Manual, Release 2.8.0-rc3
db.collection.save()
Definition
db.collection.save()
Updates an existing document or inserts a new document, depending on its document parameter.
The save() (page 70) method has the following form:
Changed in version 2.6.
db.collection.save(
<document>,
{
writeConcern: <document>
}
)
param document document A document to save to the collection.
param document writeConcern A document expressing the write concern. Omit to use the
default write concern. See Safe Writes (page 70).
New in version 2.6.
Changed in version 2.6: The save() (page 70) returns an object that contains the status of the operation.
Returns A WriteResult (page 71) object that contains the status of the operation.
Behavior
Safe Writes Changed in version 2.6.
The save() (page 70) method uses either the insert (page 247) or the update (page 251) 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 70) method calls the
insert() (page 55) method.
During the operation, the mongo (page 610) shell will create an
http://docs.mongodb.org/manual/reference/object-id 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 583) will
add the _id field and generate the ObjectId.
Update If the document contains an _id field, then the save() (page 70) method is equivalent to an update with
the upsert option (page 74) 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 70) method
performs an insert since the document passed to the method does not contain the _id field:
db.products.save( { item: "book", qty: 40 } )
70
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
During the insert,
mongod (page 583) will create the _id field with a unique
http://docs.mongodb.org/manual/reference/object-id 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 70) performs an update
with upsert:true since the document contains an _id field:
db.products.save( { _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 74) 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 70) method performs an update with upsert:true since the document contains an _id field:
db.products.save( { _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 replica set members or the method times out after 5 seconds.
db.products.save(
{ item: "envelopes", qty : 100, type: "Clasp" },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)
WriteResult Changed in version 2.6.
The save() (page 70) returns a WriteResult (page 201) object that contains the status of the insert or update
operation. See WriteResult for insert (page 57) and WriteResult for update (page 78) for details.
db.collection.stats()
Definition
db.collection.stats(scale)
Returns statistics about the collection. The method includes the following parameter:
2.1. mongo Shell Methods
71
MongoDB Reference Manual, Release 2.8.0-rc3
param number scale 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.
Returns A document that contains statistics on the specified collection.
The stats() (page 71) method provides a wrapper around the database command collStats (page 348).
Example The following operation returns stats on the people collection:
db.people.stats()
See also:
collStats (page 348) for an overview of the output of this command.
db.collection.storageSize()
db.collection.storageSize()
Returns The total amount of storage allocated to this collection for document storage. Provides
a wrapper around the storageSize (page 349) field of the collStats (page 348) (i.e.
db.collection.stats() (page 71)) output.
db.collection.totalIndexSize()
db.collection.totalIndexSize()
Returns The total size of all indexes for the collection. This method provides a wrapper
around the totalIndexSize (page 349) output of the collStats (page 348) (i.e.
db.collection.stats() (page 71)) operation.
db.collection.totalSize()
db.collection.totalSize()
Returns The total size of the data in the collection plus the size of every indexes on the collection.
db.collection.update()
Definition
db.collection.update(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 73).
By default, the update() (page 72) method updates a single document. Set the Multi Parameter (page 75) to
update all documents that match the query criteria.
The update() (page 72) method has the following form:
Changed in version 2.6.
72
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
The update() (page 72) method takes the following parameters:
param document query The selection criteria for the update.
(page 400) as used in the find() (page 36) method.
Use the same query selectors
param document update The modifications to apply. For details see Update Parameter (page 73).
param boolean upsert 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 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 75).
param document writeConcern A document expressing the write concern. Omit to use the
default write concern. See Safe Writes (page 73).
New in version 2.6.
Changed in version 2.6: The update() (page 72) method returns an object that contains the status of the
operation.
Returns A WriteResult (page 78) object that contains the status of the operation.
Behavior
Safe Writes Changed in version 2.6.
The update() (page 72) method uses the update (page 251) 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 77) for an example.
Update Parameter The update() (page 72) method either modifies specific fields in existing documents or replaces an existing document entirely.
Update Specific Fields If the <update> document contains update operator (page 451) modifiers, such as those
using the $set (page 459) modifier, then:
• The <update> document must contain only update operator (page 451) expressions.
• The update() (page 72) method updates only the corresponding fields in the document.
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.
2.1. mongo Shell Methods
73
MongoDB Reference Manual, Release 2.8.0-rc3
Replace a Document Entirely If the <update> document contains only field:value expressions, then:
• The update() (page 72) method replaces the matching document with the <update> document. The
update() (page 72) method does not replace the _id value. For an example, see Replace All Fields (page 76).
• update() (page 72) cannot update multiple documents (page 75).
Upsert Option
Upsert Behavior If upsert is true and no document matches the query criteria, update() (page 72) 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 451) 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 72) performs an update.
See also:
$setOnInsert (page 458)
Use Unique Indexes
Warning: To avoid inserting the same document more than once, only use upsert:
is uniquely indexed.
true if the query fi
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:
db.people.update(
{ name: "Andy" },
{
name: "Andy",
rating: 1,
score: 1
},
{ upsert: true }
)
If all update() (page 72) 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 72) would successfully insert a new document.
The remaining operations would either:
• update the newly inserted document, or
• 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.
74
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Multi Parameter If multi is set to true, the update() (page 72) 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 482) 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 73) document contains only field:value expressions, then update() (page 72) cannot
update multiple documents.
For an example, see Update Multiple Documents (page 77).
Sharded Collections All update() (page 72) 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 72) operations specifying multi: false in a sharded collection without the shard key or the _id field return an error.
See also:
findAndModify() (page 42)
Examples
Update Specific Fields To update specific fields in a document, use update operators (page 451) 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
}
The following operation uses:
• the $inc (page 452) operator to increment the stock field; and
• the $set (page 459) 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.
db.books.update(
{ _id: 1 },
{
$inc: { stock: 5 },
$set: {
item: "ABC123",
"info.publisher": "2222",
tags: [ "software" ],
"ratings.1": { by: "xyz", rating: 3 }
}
}
)
The updated document is the following:
2.1. mongo Shell Methods
75
MongoDB Reference Manual, Release 2.8.0-rc3
{
"_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 459), $inc (page 452), Update Operators (page 451), dot notation
Remove Fields The following operation uses the $unset (page 461) operator to remove the tags field:
db.books.update( { _id: 1 }, { $unset: { tags: 1 } } )
See also:
$unset (page 461), $rename (page 457), Update Operators (page 451)
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.
db.books.update(
{ 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 document.
{
"_id" : 2,
"item" : "XYZ123",
"stock" : 10,
"info" : { "publisher" : "2255", "pages" : 150 },
"tags" : [ "baking", "cooking" ]
}
76
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Insert a New Document if No Match Exists The following update sets the upsert (page 74) option to true so
that update() (page 72) creates a new document in the books collection if no document matches the <query>
parameter:
db.books.update(
{ 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 74).
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:
db.books.update(
{ stock: { $lte: 10 } },
{ $set: { reorder: true } },
{ multi: true }
)
If the reorder field does not exist in the matching document(s), the $set (page 459) operator will add the field
with the specified value. See $set (page 459) 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 replica set members or the method times out after 5 seconds.
db.books.update(
{ 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",
2.1. mongo Shell Methods
77
MongoDB Reference Manual, Release 2.8.0-rc3
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.
db.books.update(
{ 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,
"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 74).
WriteResult Changed in version 2.6.
Successful Results The update() (page 72) method returns a WriteResult (page 201) object that contains the
status of the operation. Upon success, the WriteResult (page 201) 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:
78
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
See
WriteResult.nMatched (page 201), WriteResult.nUpserted (page 201), WriteResult.nModified
(page 201)
Write Concern Errors If the update() (page 72) method encounters write concern errors, the results include the
WriteResult.writeConcernError (page 201) field:
WriteResult({
"nMatched" : 1,
"nUpserted" : 0,
"nModified" : 1,
"writeConcernError" : {
"code" : 64,
"errmsg" : "waiting for replication timed out at shard-a"
}
})
See also:
WriteResult.hasWriteConcernError() (page 202)
Errors Unrelated to Write Concern If the update() (page 72) method encounters a non-write concern error, the
results include the WriteResult.writeError (page 201) field:
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 7,
"errmsg" : "could not contact primary for replica set shard-a"
}
})
See also:
WriteResult.hasWriteError() (page 202)
db.collection.validate()
Description
db.collection.validate(full)
Validates a collection. The method scans a collection’s 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 79) method has the following parameter:
param Boolean full Specify true to enable a full validation and to return full statistics. MongoDB
disables full validation by default because it is a potentially resource-intensive operation.
2.1. mongo Shell Methods
79
MongoDB Reference Manual, Release 2.8.0-rc3
The validate() (page 79) 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 79) method is a wrapper around the validate (page 389) database command.
See also:
validate (page 389)
80
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
2.1.2 Cursor
Cursor Methods
Name
Description
cursor.addOption() Adds special wire protocol flags that modify the behavior of the query.’
(page 81)
cursor.batchSize() Controls the number of documents MongoDB will return to the client in a single
(page 82)
network message.
cursor.count()
Returns a count of the documents in a cursor.
(page 83)
cursor.explain()
Reports on the query execution plan, including index use, for a cursor.
(page 85)
cursor.forEach()
Applies a JavaScript function for every document in a cursor.
(page 86)
cursor.hasNext()
Returns true if the cursor has documents and can be iterated.
(page 87)
cursor.hint()
Forces MongoDB to use a specific index for a query.
(page 87)
cursor.limit()
Constrains the size of a cursor’s result set.
(page 88)
cursor.map()
Applies a function to each document in a cursor and collects the return values in an
(page 88)
array.
cursor.max()
Specifies an exclusive upper index bound for a cursor. For use with
(page 88)
cursor.hint() (page 87)
cursor.maxTimeMS() Specifies a cumulative time limit in milliseconds for processing operations on a
(page 90)
cursor.
cursor.min()
Specifies an inclusive lower index bound for a cursor. For use with
(page 91)
cursor.hint() (page 87)
cursor.next()
Returns the next document in a cursor.
(page 93)
cursor.objsLeftInBatch()
Returns the number of documents left in the current cursor batch.
(page 93)
cursor.readPref() Specifies a read preference to a cursor to control how the client directs queries to a
(page 93)
replica set.
cursor.showDiskLoc()Returns a cursor with modified documents that include the on-disk location of the
(page 93)
document.
cursor.size()
Returns a count of the documents in the cursor after applying skip() (page 94) and
(page 94)
limit() (page 88) methods.
cursor.skip()
Returns a cursor that begins returning results only after passing or skipping a number
(page 94)
of documents.
cursor.snapshot() Forces the cursor to use the index on the _id field. Ensures that the cursor returns
(page 95)
each document, with regards to the value of the _id field, only once.
cursor.sort()
Returns results ordered according to a sort specification.
(page 95)
cursor.toArray()
Returns an array that contains all documents returned by the cursor.
(page 99)
cursor.addOption()
Definition
cursor.addOption(flag)
Adds OP_QUERY wire protocol flags, such as the tailable flag, to change the behavior of queries.
2.1. mongo Shell Methods
81
MongoDB Reference Manual, Release 2.8.0-rc3
The cursor.addOption() (page 81) method has the following parameter:
param flag flag OP_QUERY wire protocol flag. See MongoDB wire protocol6 for more information on MongoDB Wire Protocols and the OP_QUERY flags. For the mongo (page 610)
shell, you can use cursor flags (page 82). For the driver-specific list, see your driver
documentation.
Flags The mongo (page 610) shell provides several additional cursor flags to modify the behavior of the cursor.
DBQuery.Option.tailable
DBQuery.Option.slaveOk
DBQuery.Option.oplogReplay
DBQuery.Option.noTimeout
DBQuery.Option.awaitData
DBQuery.Option.exhaust
DBQuery.Option.partial
For a description of the flags, see MongoDB wire protocol7 .
Example The
following
example
adds
the
DBQuery.Option.tailable
flag
and
the
DBQuery.Option.awaitData flag to ensure that the query returns a tailable cursor. The sequence creates 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 = db.myCappedCollection;
var cursor = t.find().addOption(DBQuery.Option.tailable).
addOption(DBQuery.Option.awaitData)
Warning: Adding incorrect wire protocol flags can cause problems and/or extra server load.
cursor.batchSize()
Definition
cursor.batchSize(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 610) shell and
most drivers return results as if MongoDB returned a single batch.
The batchSize() (page 82) method takes the following parameter:
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 88) method.
6 http://docs.mongodb.org/meta-driver/latest/legacy/mongodb-wire-protocol/?pageVersion=106#op-query
7 http://docs.mongodb.org/meta-driver/latest/legacy/mongodb-wire-protocol/?pageVersion=106#op-query
82
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Example The following example sets the batch size for the results of a query (i.e. find() (page 36)) to 10. The
batchSize() (page 82) method does not change the output in the mongo (page 610) shell, which, by default,
iterates over the first 20 documents.
db.inventory.find().batchSize(10)
cursor.count()
Definition
cursor.count()
Counts the number of documents referenced by a cursor. Append the count() (page 83) method to a find()
(page 36) 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 87) with count() (page 83). See
Specify the Index to Use (page 84) for an example.
The count() (page 83) method has the following prototype form:
db.collection.find(<query>).count()
The count() (page 83) method has the following parameter:
param Boolean applySkipLimit Specifies whether to consider the effects of the
cursor.skip() (page 94) and cursor.limit() (page 88) methods in the count.
By default, the count() (page 83) method ignores the effects of the cursor.skip()
(page 94) and cursor.limit() (page 88). Set applySkipLimit to true to consider
the effect of these methods.
MongoDB also provides an equivalent db.collection.count() (page 26) as an alternative to the
db.collection.find(<query>).count() construct.
See also:
cursor.size() (page 94)
Behavior
Sharded Clusters On a sharded cluster, count() (page 83) method 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 486) stage of the
db.collection.aggregate() (page 22) method to $sum (page 554) the documents. For example, the
following operation counts the documents in a collection:
db.collection.aggregate(
[
{ $group: { _id: null, count: { $sum: 1 } } }
]
)
To get a count of documents that match a query condition, include the $match (page 490) stage as well:
db.collection.aggregate(
[
{ $match: <query condition> },
{ $group: { _id: null, count: { $sum: 1 } } }
2.1. mongo Shell Methods
83
MongoDB Reference Manual, Release 2.8.0-rc3
]
)
See Perform a Count (page 491) 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:
db.collection.find( { a: 5, b: 5 } ).count()
db.collection.find( { a: { $gt: 5 } } ).count()
db.collection.find( { 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.
db.collection.find( { a: 5, b: { $in: [ 1, 2, 3 ] } } ).count()
db.collection.find( { a: { $gt: 5 }, b: 5 } ).count()
db.collection.find( { 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 subsequent calls of the same count operation will have better performance.
Examples The following are examples of the count() (page 83) method.
Count All Documents The following operation counts the number of all documents in the orders collection:
db.orders.find().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’):
db.orders.find( { 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):
db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).limit(5).count(true)
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":
84
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.orders.find(
{ ord_dt: { $gt: new Date('01/01/2012') }, status: "D" }
).hint( "status_1" ).count()
cursor.explain()
Definition
cursor.explain(verbosity)
Changed in version 2.8: The parameter to the method and the output format have changed in 2.8.
Provides information on the query plan for the db.collection.find() (page 36) method.
The explain() (page 85) method has the following form:
db.collection.find().explain()
The explain() (page 85) method has the following parameter:
param String verbose 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 cursor.explain() (page 85), MongoDB interprets true as "allPlansExecution" and false as "queryPlanner".
For more information on the modes, see Verbosity Modes (page 85).
Changed in version 2.8.
The explain() (page 85) method returns a document with the query plan and, optionally, the execution
statistics.
Behavior
Verbosity Modes The behavior of cursor.explain() (page 85) and the amount of information returned depend
on the verbosity mode.
queryPlanner Mode By default, cursor.explain() (page 85) runs in queryPlanner verbosity mode.
MongoDB runs the query optimizer to choose the winning plan for the operation under evaluation.
cursor.explain() (page 85) returns the queryPlanner 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, cursor.explain() (page 85) returns information about the update or delete operations that
would be performed, but does not apply the modifications to the database.
cursor.explain() (page 85) returns the queryPlanner and executionStats information for the evaluated method. However, executionStats does not provide query execution information for the rejected plans.
2.1. mongo Shell Methods
85
MongoDB Reference Manual, Release 2.8.0-rc3
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, cursor.explain() (page 85) returns information about the update or delete operations that
would be performed, but does not apply the modifications to the database.
cursor.explain() (page 85) returns the queryPlanner and executionStats information for the evaluated method. The executionStats includes the completed query execution information for the winning plan.
If the query optimizer considered more than one plan, executionStats information also includes the partial
execution information captured during the plan selection phase for both the winning and rejected candidate plans.
db.collection.explain().find() db.collection.explain().find()
db.collection.find().explain() (page 85) with the following key differences:
is
similar
to
• The db.collection.explain().find() construct allows for the additional chaining of query modifiers. For list of query modifiers, see db.collection.explain().find().help() (page 35).
• The db.collection.explain().find() returns a cursor, which requires a call to .next(), or its
alias .finish(), to return the explain() results.
See db.collection.explain() (page 33) for more information.
Example The following example runs cursor.explain() (page 85) in “executionStats” (page 34) verbosity
mode to return the query planning and execution information for the specified db.collection.find() (page 36)
operation:
db.products.find(
{ quantity: { $gt: 50 }, category: "apparel" }
).explain("executionStats")
Output cursor.explain() (page 85) operations can return information regarding:
• queryPlanner, which details the plan selected by the query optimizer and lists the rejected plans;
• executionStats, which details the execution of the winning plan and the rejected plans; and
• serverInfo, which provides information on the MongoDB instance.
The verbosity mode (i.e. queryPlanner, executionStats, allPlansExecution) determines whether the
results include executionStats and whether executionStats includes data captured during plan selection.
For details on the output, see http://docs.mongodb.org/manual/reference/explain-results.
For a mixed version sharded cluster with version 2.8 mongos (page 601) and at least one 2.6 mongod
(page 583) shard, when you run cursor.explain() (page 85) in a version 2.8 mongo (page 610) shell,
cursor.explain() (page 85) will retry with the $explain (page 556) operator to return results in the 2.6
format.
cursor.forEach()
Description
cursor.forEach(function)
Iterates the cursor to apply a JavaScript function to each document from the cursor.
The forEach() (page 86) method has the following prototype form:
86
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.collection.find().forEach(<function>)
The forEach() (page 86) 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 process.
Example The following example invokes the forEach() (page 86) method on the cursor returned by find()
(page 36) to print the name of each user in the collection:
db.users.find().forEach( function(myDoc) { print( "user: " + myDoc.name ); } );
See also:
cursor.map() (page 88) for similar functionality.
cursor.hasNext()
cursor.hasNext()
Returns Boolean.
cursor.hasNext() (page 87) returns true if the cursor returned by the db.collection.find()
(page 36) query can iterate further to return more documents.
cursor.hint()
Definition
cursor.hint(index)
Call this method on a query to override MongoDB’s default index selection and query optimization
process. Use db.collection.getIndexes() (page 48) to return the list of current indexes on a collection.
The cursor.hint() (page 87) 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 87).
You cannot use hint() (page 87) if the query includes a $text (page 417) query expression.
Example The following example returns all documents in the collection named users using the index on the age
field.
db.users.find().hint( { age: 1 } )
You can also specify the index using the index name:
db.users.find().hint( "age_1" )
See also:
• http://docs.mongodb.org/manual/core/indexes-introduction
2.1. mongo Shell Methods
87
MongoDB Reference Manual, Release 2.8.0-rc3
• http://docs.mongodb.org/manual/administration/indexes
• http://docs.mongodb.org/manual/core/query-plans
• index-filters
• $hint (page 556)
cursor.limit()
Definition
cursor.limit()
Use the limit() (page 88) method on a cursor to specify the maximum number of documents the cursor will
return. limit() (page 88) is analogous to the LIMIT statement in a SQL database.
Note: You must apply limit() (page 88) to the cursor before retrieving any documents from the database.
Use limit() (page 88) to maximize performance and prevent MongoDB from returning more results than
required for processing.
Behavior
Supported Values The behavior of limit() (page 88) is undefined for values less than -231 and greater than 231 .
Negative Values A limit() (page 88) value of 0 (i.e. .limit(0) (page 88)) is equivalent to setting no limit. A
negative limit is similar to a positive limit, but a negative limit prevents the creation of a cursor such that only a single
batch of results is returned. 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 limit.
cursor.map()
cursor.map(function)
Applies function to each document visited by the cursor and collects the return values from successive
application into an array.
The cursor.map() (page 88) method has the following parameter:
param function function A function to apply to each document visited by the cursor.
Example
db.users.find().map( function(u) { return u.name; } );
See also:
cursor.forEach() (page 86) for similar functionality.
cursor.max()
Definition
88
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
cursor.max()
Specifies the exclusive upper bound for a specific index in order to constrain the results of find() (page 36).
max() (page 88) provides a way to specify an upper bound on compound key indexes.
The max() (page 88) 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 87) method. Otherwise, mongod (page 583) 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 91).
max() (page 88) exists primarily to support the mongos (page 601) (sharding) process, and is a shell wrapper
around the query modifier $max (page 558).
Behavior
Interaction with Index Selection Because max() (page 88) requires an index on a field, and forces the query to
use this index, you may prefer the $lt (page 403) operator for the query if possible. Consider the following example:
db.products.find( { _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 88) with min() (page 91) to specify a range, the index bounds specified in
min() (page 91) and max() (page 88) 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.
If one of the two boundaries is not specified, then 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"
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
:
:
:
:
:
:
:
:
:
:
6, "item" : "apple", "type" : "cortland", "price" : 1.29 }
2, "item" : "apple", "type" : "fuji", "price" : 1.99 }
1, "item" : "apple", "type" : "honey crisp", "price" : 1.99 }
3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }
4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }
5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }
7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }
10, "item" : "orange", "type" : "navel", "price" : 1.39 }
9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }
8, "item" : "orange", "type" : "valencia", "price" : 0.99 }
2.1. mongo Shell Methods
89
MongoDB Reference Manual, Release 2.8.0-rc3
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 88) limits the query to the documents that are below the bound of item equal to apple and type equal to jonagold:
db.products.find().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 87) method, it is ambiguous as to whether
mongod (page 583) 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 88) limits the query to the documents that are
below the index key bound of price equal to 1.99 and min() (page 91) limits the query to the documents
that are at or above the index key bound of price equal to 1.39:
db.products.find().min( { price: 1.39 } ).max( { price: 1.99 } ).hint( { price: 1 } )
The query returns the following documents:
{
{
{
{
{
"_id"
"_id"
"_id"
"_id"
"_id"
:
:
:
:
:
6, "item" : "apple", "type" :
4, "item" : "apple", "type" :
5, "item" : "apple", "type" :
3, "item" : "apple", "type" :
10, "item" : "orange", "type"
"cortland", "price" : 1.29 }
"jonathan", "price" : 1.29 }
"mcintosh", "price" : 1.29 }
"jonagold", "price" : 1.29 }
: "navel", "price" : 1.39 }
cursor.maxTimeMS()
Definition New in version 2.6.
cursor.maxTimeMS(<time limit>)
Specifies a cumulative time limit in milliseconds for processing operations on a cursor.
The maxTimeMS() (page 90) method has the following parameter:
param integer milliseconds Specifies a cumulative time limit in milliseconds for processing operations on the cursor.
Important: maxTimeMS() (page 90) is not related to the NoCursorTimeout query flag. maxTimeMS()
(page 90) relates to processing time, while NoCursorTimeout relates to idle time. A cursor’s 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 db.killOp()
(page 119). MongoDB only terminates an operation at one of its designated interrupt points.
MongoDB does not count network latency towards a cursor’s time limit.
90
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
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:
db.collection.find({description: /August [0-9]+, 1969/}).maxTimeMS(50)
cursor.min()
Definition
cursor.min()
Specifies the inclusive lower bound for a specific index in order to constrain the results of find() (page 36).
min() (page 91) provides a way to specify lower bounds on compound key indexes.
The min() (page 91) 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 87) 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 88).
min() (page 91) exists primarily to support the mongos (page 601) process, and is a shell wrapper around the
query modifier $min (page 559).
Behaviors
Interaction with Index Selection Because min() (page 91) requires an index on a field, and forces the query to use
this index, you may prefer the $gte (page 401) operator for the query if possible. Consider the following example:
db.products.find( { _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 91) with max() (page 88) to specify a range, the index bounds specified in
min() (page 91) and max() (page 88) 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.
2.1. mongo Shell Methods
91
MongoDB Reference Manual, Release 2.8.0-rc3
If one of the two boundaries is not specified, then 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"
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
:
:
:
:
:
:
:
:
:
:
6, "item" : "apple", "type" : "cortland", "price" : 1.29 }
2, "item" : "apple", "type" : "fuji", "price" : 1.99 }
1, "item" : "apple", "type" : "honey crisp", "price" : 1.99 }
3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }
4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }
5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }
7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }
10, "item" : "orange", "type" : "navel", "price" : 1.39 }
9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }
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 91) 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:
db.products.find().min( { item: 'apple', type: 'jonagold' } ).hint( { item: 1, type: 1 } )
The query returns the following documents:
{
{
{
{
{
{
{
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
:
:
:
:
:
:
:
3, "item" : "apple", "type" : "jonagold", "price" : 1.29 }
4, "item" : "apple", "type" : "jonathan", "price" : 1.29 }
5, "item" : "apple", "type" : "mcintosh", "price" : 1.29 }
7, "item" : "orange", "type" : "cara cara", "price" : 2.99 }
10, "item" : "orange", "type" : "navel", "price" : 1.39 }
9, "item" : "orange", "type" : "satsuma", "price" : 1.99 }
8, "item" : "orange", "type" : "valencia", "price" : 0.99 }
If the query did not explicitly specify the index with the hint() (page 87) method, it is ambiguous as to whether
mongod (page 583) 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 91) limits the query to the documents that
are at or above the index key bound of price equal to 1.39 and max() (page 88) limits the query to the
documents that are below the index key bound of price equal to 1.99:
db.products.find().min( { price: 1.39 } ).max( { price: 1.99 } ).hint( { price: 1 } )
The query returns the following documents:
{
{
{
{
{
92
"_id"
"_id"
"_id"
"_id"
"_id"
:
:
:
:
:
6, "item" : "apple", "type" :
4, "item" : "apple", "type" :
5, "item" : "apple", "type" :
3, "item" : "apple", "type" :
10, "item" : "orange", "type"
"cortland", "price" : 1.29 }
"jonathan", "price" : 1.29 }
"mcintosh", "price" : 1.29 }
"jonagold", "price" : 1.29 }
: "navel", "price" : 1.39 }
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
cursor.next()
cursor.next()
Returns The next document in the cursor returned by the db.collection.find() (page 36)
method. See cursor.hasNext() (page 87) related functionality.
cursor.objsLeftInBatch()
cursor.objsLeftInBatch()
cursor.objsLeftInBatch() (page 93) 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.
cursor.readPref()
Definition
cursor.readPref(mode, tagSet)
Append readPref() (page 93) 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:
primaryPreferred, secondary, secondaryPreferred, or nearest
primary,
param array tagSet 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 93) to the cursor before retrieving any documents from the
database.
cursor.showDiskLoc()
cursor.showDiskLoc()
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>
}
cursor.showDiskLoc() (page 93) method is a wrapper around $showDiskLoc (page 561).
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 93) method to the
db.collection.find() (page 36) method in order to include in the matching documents the disk location information:
2.1. mongo Shell Methods
93
MongoDB Reference Manual, Release 2.8.0-rc3
db.collection.find( { 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 }
}
{
"_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:
db.collection.find( { 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 561) for related functionality.
cursor.size()
cursor.size()
Returns A count of the number of documents that match the db.collection.find()
(page 36) query after applying any cursor.skip() (page 94) and cursor.limit()
(page 88) methods.
cursor.skip()
cursor.skip()
Call the cursor.skip() (page 94) method on a cursor to control where MongoDB begins returning results.
This approach may be useful in implementing “paged” results.
Note: You must apply cursor.skip() (page 94) to the cursor before retrieving any documents from the
database.
Consider the following JavaScript function as an example of the skip function:
94
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
function printStudents(pageNumber, nPerPage) {
print("Page: " + pageNumber);
db.students.find().skip(pageNumber > 0 ? ((pageNumber-1)*nPerPage) : 0).limit(nPerPage).forEa
}
The cursor.skip() (page 94) 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, cursor.skip() (page 94) will become slower and more CPU
intensive. With larger collections, cursor.skip() (page 94) may become IO bound.
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.
cursor.snapshot()
cursor.snapshot()
Append the snapshot() (page 95) 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 95) to the cursor before retrieving any documents from the
database.
•You can only use snapshot() (page 95) with unsharded collections.
The snapshot() (page 95) does not guarantee isolation from insertion or deletions.
The snapshot() (page 95) traverses the index on the _id field. As such, snapshot() (page 95) cannot
be used with sort() (page 95) or hint() (page 87).
Queries with results of less than 1 megabyte are effectively implicitly snapshotted.
cursor.sort()
Definition
cursor.sort(sort)
Specifies the order in which the query returns matching documents. You must apply sort() (page 95) to the
cursor before retrieving any documents from the database.
The sort() (page 95) 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 96) or sort on computed
metadata (page 96).
Behaviors
2.1. mongo Shell Methods
95
MongoDB Reference Manual, Release 2.8.0-rc3
Result Ordering Unless you specify the sort() (page 95) method or use the $near (page 429) operator, MongoDB 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 }
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, Timestamp
11. Regular Expression
12. MaxKey (internal type)
MongoDB treats some types as equivalent for comparison purposes. For instance, numeric types undergo conversion
before comparison.
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 449) expression as its value.
The following sample document specifies a descending sort by the "textScore" metadata:
{ score: { $meta: "textScore" } }
96
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
The specified metadata determines the sort order. For example, the "textScore" metadata sorts in descending
order. See $meta (page 449) for details.
Limit Results The sort operation requires that the entire sort be able to complete within 32 megabytes.
When the sort operation consumes more than 32 megabytes, MongoDB returns an error. To avoid this error, either
create an index to support the sort operation or use sort() (page 95) in conjunction with limit() (page 88). The
specified limit must result in a number of documents that fall within the 32 megabyte limit.
For example, if the following sort operation stocks_quotes exceeds the 32 megabyte limit:
db.stocks.find().sort( { ticker: 1, date: -1 } )
Either create an index to support the sort operation:
db.stocks.ensureIndex( { ticker: 1, date: -1 } )
Or use sort() (page 95) in conjunction with limit() (page 88):
db.stocks.find().sort( { ticker: 1, date: -1 } ).limit(100)
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:
_id:
_id:
_id:
_id:
_id:
1,
2,
3,
4,
5,
6,
item:
item:
item:
item:
item:
item:
{
{
{
{
{
{
category:
category:
category:
category:
category:
category:
"cake", type: "chiffon" }, amount: 10 }
"cookies", type: "chocolate chip" }, amount: 50 }
"cookies", type: "chocolate chip" }, amount: 15 }
"cake", type: "lemon" }, amount: 30 }
"cake", type: "carrot" }, amount: 20 }
"brownies", type: "blondie" }, amount: 10 }
The following query, which returns all documents from the orders collection, does not specify a sort order:
db.orders.find()
The query returns the documents in indeterminate order:
{
{
{
{
{
{
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
:
:
:
:
:
:
1,
2,
3,
4,
5,
6,
"item"
"item"
"item"
"item"
"item"
"item"
:
:
:
:
:
:
{
{
{
{
{
{
"category"
"category"
"category"
"category"
"category"
"category"
:
:
:
:
:
:
"cake", "type" : "chiffon" }, "amount" : 10 }
"cookies", "type" : "chocolate chip" }, "amount" : 50 }
"cookies", "type" : "chocolate chip" }, "amount" : 15 }
"cake", "type" : "lemon" }, "amount" : 30 }
"cake", "type" : "carrot" }, "amount" : 20 }
"brownies", "type" : "blondie" }, "amount" : 10 }
The following query specifies a sort on the amount field in descending order.
db.orders.find().sort( { amount: -1 } )
The query returns the following documents, in descending order of amount:
{
{
{
{
{
{
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
:
:
:
:
:
:
2,
4,
5,
3,
1,
6,
"item"
"item"
"item"
"item"
"item"
"item"
:
:
:
:
:
:
{
{
{
{
{
{
2.1. mongo Shell Methods
"category"
"category"
"category"
"category"
"category"
"category"
:
:
:
:
:
:
"cookies", "type" : "chocolate chip" }, "amount" : 50 }
"cake", "type" : "lemon" }, "amount" : 30 }
"cake", "type" : "carrot" }, "amount" : 20 }
"cookies", "type" : "chocolate chip" }, "amount" : 15 }
"cake", "type" : "chiffon" }, "amount" : 10 }
"brownies", "type" : "blondie" }, "amount" : 10 }
97
MongoDB Reference Manual, Release 2.8.0-rc3
The following query specifies the sort order using the fields from a sub-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.
db.orders.find().sort( { "item.category": 1, "item.type": 1 } )
The query returns the following documents, ordered first by the category field, and within each category, by the
type field:
{
{
{
{
{
{
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
:
:
:
:
:
:
6,
5,
1,
4,
2,
3,
"item"
"item"
"item"
"item"
"item"
"item"
:
:
:
:
:
:
{
{
{
{
{
{
"category"
"category"
"category"
"category"
"category"
"category"
:
:
:
:
:
:
"brownies", "type" : "blondie" }, "amount" : 10 }
"cake", "type" : "carrot" }, "amount" : 20 }
"cake", "type" : "chiffon" }, "amount" : 10 }
"cake", "type" : "lemon" }, "amount" : 30 }
"cookies", "type" : "chocolate chip" }, "amount" : 50 }
"cookies", "type" : "chocolate chip" }, "amount" : 15 }
Return in Natural Order The $natural (page 563) 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.
Typically, the natural order reflects insertion order, except when documents relocate because of document growth due
to updates or remove operations free up space which are then taken up by newly inserted documents.
Consider the sequence of insert operations to the trees collection:
db.trees.insert(
db.trees.insert(
db.trees.insert(
db.trees.insert(
{
{
{
{
_id:
_id:
_id:
_id:
1,
2,
3,
4,
common_name:
common_name:
common_name:
common_name:
"oak", genus: "quercus" } )
"chestnut", genus: "castanea" } )
"maple", genus: "aceraceae" } )
"birch", genus: "betula" } )
The following query returns the documents in the natural order:
db.trees.find().sort( { $natural: 1 } )
The documents return in the following order:
{
{
{
{
"_id"
"_id"
"_id"
"_id"
:
:
:
:
1,
2,
3,
4,
"common_name"
"common_name"
"common_name"
"common_name"
:
:
:
:
"oak", "genus" : "quercus" }
"chestnut", "genus" : "castanea" }
"maple", "genus" : "aceraceae" }
"birch", "genus" : "betula" }
Update a document such that the document outgrows its current allotted space:
db.trees.update(
{ _id: 1 },
{ $set: { famous_oaks: [ "Emancipation Oak", "Goethe Oak" ] } }
)
Rerun the query to returns the documents in natural order:
db.trees.find().sort( { $natural: 1 } )
The documents return in the following natural order:
{
{
{
{
"_id"
"_id"
"_id"
"_id"
:
:
:
:
2,
3,
4,
1,
"common_name"
"common_name"
"common_name"
"common_name"
:
:
:
:
"chestnut", "genus" : "castanea" }
"maple", "genus" : "aceraceae" }
"birch", "genus" : "betula" }
"oak", "genus" : "quercus", "famous_oaks" : [ "Emancipation Oak", "Goeth
See also:
$natural (page 563)
98
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
cursor.toArray()
cursor.toArray()
The toArray() (page 99) 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 99) to the cursor returned from the find() (page 36)
method:
var allProductsArray = db.products.find().toArray();
if (allProductsArray.length > 0) { printjson (allProductsArray[0]); }
The variable allProductsArray holds the array of documents returned by toArray() (page 99).
2.1.3 Database
Database Methods
Name
db.auth() (page 100)
db.changeUserPassword() (page 152)
db.cloneCollection() (page 101)
db.cloneDatabase() (page 101)
db.commandHelp() (page 101)
db.copyDatabase() (page 102)
db.createCollection() (page 104)
db.currentOp() (page 105)
db.dropDatabase() (page 111)
db.eval() (page 112)
db.fsyncLock() (page 113)
db.fsyncUnlock() (page 114)
db.getCollection() (page 114)
db.getCollectionNames() (page 114)
db.getLastError() (page 114)
db.getLastErrorObj() (page 115)
db.getLogComponents() (page 115)
db.getMongo() (page 116)
db.getName() (page 116)
db.getPrevError() (page 116)
db.getProfilingLevel() (page 117)
db.getProfilingStatus() (page 117)
db.getReplicationInfo() (page 117)
db.getSiblingDB() (page 118)
db.help() (page 118)
db.hostInfo() (page 119)
db.isMaster() (page 119)
db.killOp() (page 119)
db.listCommands() (page 120)
db.loadServerScripts() (page 120)
db.logout() (page 120)
2.1. mongo Shell Methods
Description
Authenticates a user to a database.
Changes an existing user’s password.
Copies data directly between MongoDB instances. Wraps cloneCollec
Copies a database from a remote host to the current host. Wraps clone (p
Returns help information for a database command.
Copies a database to another database on the current host. Wraps copydb
Creates a new collection. Commonly used to create a capped collection.
Reports the current in-progress operations.
Removes the current database.
Passes a JavaScript function to the mongod (page 583) instance for serverFlushes writes to disk and locks the database to prevent write operations an
Allows writes to continue on a database locked with db.fsyncLock() (
Returns a collection object. Used to access collections with names that are
Lists all collections in the current database.
Checks and returns the status of the last operation. Wraps getLastErro
Returns the status document for the last operation. Wraps getLastErro
Returns the log message verbosity levels.
Returns the Mongo() (page 202) connection object for the current connec
Returns the name of the current database.
Returns a status document containing all errors since the last error reset. W
Returns the current profiling level for database operations.
Returns a document that reflects the current profiling level and the profiling
Returns a document with replication statistics.
Provides access to the specified database.
Displays descriptions of common db object methods.
Returns a document with information about the system MongoDB runs on.
Returns a document that reports the state of the replica set.
Terminates a specified operation.
Displays a list of common database commands.
Loads all scripts in the system.js collection for the current database int
Ends an authenticated session.
99
MongoDB Reference Manual, Release 2.8.0-rc3
Name
db.printCollectionStats() (page 121)
db.printReplicationInfo() (page 121)
db.printShardingStatus() (page 122)
db.printSlaveReplicationInfo() (page 122)
db.removeUser() (page 157)
db.repairDatabase() (page 123)
db.resetError() (page 123)
db.runCommand() (page 123)
db.serverBuildInfo() (page 124)
db.serverCmdLineOpts() (page 124)
db.serverStatus() (page 124)
db.setLogLevel() (page 124)
db.setProfilingLevel() (page 126)
db.shutdownServer() (page 126)
db.stats() (page 126)
db.upgradeCheck() (page 127)
db.upgradeCheckAllDBs() (page 128)
db.version() (page 130)
Table 2.2 – continued from previous page
Description
Prints statistics from every collection. Wraps db.collection.stats(
Prints a report of the status of the replica set from the perspective of the pri
Prints a report of the sharding configuration and the chunk ranges.
Prints a report of the status of the replica set from the perspective of the sec
Removes a user from a database.
Runs a repair routine on the current database.
Resets the error message returned by db.getPrevError() (page 116)
Runs a database command (page 210).
Returns a document that displays the compilation parameters for the mong
Returns a document with information about the runtime used to start the M
Returns a document that provides an overview of the state of the database p
Sets a single log message verbosity level.
Modifies the current level of database profiling.
Shuts down the current mongod (page 583) or mongos (page 601) proces
Returns a document that reports on the state of the current database.
Performs a preliminary check for upgrade preparedness for a specific datab
Performs a preliminary check for upgrade preparedness for all databases an
Returns the version of the mongod (page 583) instance.
db.auth()
Definition
db.auth(username, password)
Allows a user to authenticate to the database from within the shell.
param string username Specifies an existing username with access privileges for this database.
param string password Specifies the corresponding password.
param string mechanism Specifies the authentication mechanism used.
Defaults to
MONGODB-CR. PLAIN is used for SASL/LDAP authentication, available only in
MongoDB Enterprise.
Alternatively, you can use mongo --username, --password, and --authenticationMechanism
to specify authentication credentials.
--authenticationMechanism supports additional mechanisms not available when using db.auth()
(page 100).
Note: The mongo (page 610) shell excludes all db.auth() (page 100) operations from the saved history.
Returns db.auth() (page 100) returns 0 when authentication is not successful, and 1 when the
operation is successful.
db.changeUserPassword()
Definition
db.changeUserPassword(username, password)
Updates a user’s password.
param string username Specifies an existing username with access privileges for this database.
param string password Specifies the corresponding password.
100
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
param string mechanism Specifies the authentication mechanism used.
Defaults to
MONGODB-CR. PLAIN is used for SASL/LDAP authentication, available only in
MongoDB Enterprise.
Example The following operation changes the reporting user’s password to SOh3TbYhx8ypJPxmt1oOfL:
db.changeUserPassword("reporting", "SOh3TbYhx8ypJPxmt1oOfL")
db.cloneCollection()
Definition
db.cloneCollection(from, collection, query)
Copies data directly between MongoDB instances. The db.cloneCollection() (page 101) wraps the
cloneCollection (page 320) database command and accepts the following arguments:
param string from Host name of the MongoDB instance that holds the collection to copy.
param string collection The collection in the MongoDB instance that you want to copy.
db.cloneCollection() (page 101) 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 320) directly.
param document query A standard query document that limits the documents copied as part of the
db.cloneCollection() (page 101) operation. All query selectors (page 400) available to
the find() (page 36) are available here.
db.cloneCollection() (page 101) does not allow you to clone a collection through a mongos
(page 601). You must connect directly to the mongod (page 583) instance.
db.cloneDatabase()
Definition
db.cloneDatabase(“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 320).” The copydb
(page 326) database command provides related functionality.
Example To clone a database named importdb on a host named hostname, issue the following:
use importdb
db.cloneDatabase("hostname")
New databases are implicitly created, so the current host does not need to have a database named importdb for this
command to succeed.
db.commandHelp()
Description
2.1. mongo Shell Methods
101
MongoDB Reference Manual, Release 2.8.0-rc3
db.commandHelp(command)
Displays help text for the specified database command. See the Database Commands (page 210).
The db.commandHelp() (page 101) method has the following parameter:
param string command The name of a database command.
db.copyDatabase()
Definition
db.copyDatabase(fromdb, todb, fromhost, username, password)
Copies a database from a remote host to the current host or copies a database to another database within the
current host. db.copyDatabase() (page 102) wraps the copydb (page 326) command and takes the
following arguments:
param string fromdb The name of the source database.
param string todb The name of the destination database.
param string fromhost The name of the source database host. Omit the hostname to copy from one
database to another on the same server.
field string username The username credentials on the fromhost for authentication and authorization.
field string password The password on the fromhost for authentication and authorization. The
method does not transmit the password in plaintext.
Behavior Be aware of the following properties of db.copyDatabase() (page 102):
• db.copyDatabase() (page 102) runs on the destination mongod (page 583) instance, i.e. the host receiving
the copied data.
• If the destination mongod (page 583) has authorization enabled, db.copyDatabase() (page 102)
must specify the credentials of a user present in the source database who has the privileges described in Required
Access (page 102).
• db.copyDatabase() (page 102) creates the target database if it does not exist.
• db.copyDatabase() (page 102) requires enough free disk space on the host instance for the copied
database. Use the db.stats() (page 126) operation to check the size of the database on the source mongod
(page 583) instance.
• db.copyDatabase() (page 102) and clone (page 320) 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 divergent data sets.
• db.copyDatabase() (page 102) does not lock the destination server during its operation, so the copy will
occasionally yield to allow other operations to complete.
Required Access Changed in version 2.6.
The copydb (page 326) command requires the following authorization on the target and source databases.
Source Database (fromdb)
102
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Source is non-admin Database If the source database is a non-admin database, you must have privileges that
specify find action on the source database, and find action on the system.js collection in the source database.
For example:
{ resource: { db: "mySourceDB", collection: "" }, actions: [ "find" ] }
{ resource: { db: "mySourceDB", collection: "system.js" }, actions: [ "find" ] }
If the source database is on a remote server, you also need the find action on the system.indexes and
system.namespaces collections in the source database; e.g.
{ resource: { db: "mySourceDB", collection: "system.indexes" }, actions: [ "find" ] }
{ resource: { db: "mySourceDB", collection: "system.namespaces" }, actions: [ "find" ] }
Source is admin Database If the source database is the admin database, you must have privileges that specify
find action on the admin database, and find action on the system.js, system.users, system.roles,
and system.version collections in the admin database. For example:
{
{
{
{
{
resource:
resource:
resource:
resource:
resource:
{
{
{
{
{
db:
db:
db:
db:
db:
"admin",
"admin",
"admin",
"admin",
"admin",
collection:
collection:
collection:
collection:
collection:
"" }, actions: [ "find" ] }
"system.js" }, actions: [ "find" ] }
"system.users" }, actions: [ "find" ] }
"system.roles" }, actions: [ "find" ] }
"system.version" }, actions: [ "find" ] }
If the source database is on a remote server, the you also need the find action on the system.indexes and
system.namespaces collections in the admin database; e.g.
{ resource: { db: "admin", collection: "system.indexes" }, actions: [ "find" ] }
{ resource: { db: "admin", collection: "system.namespaces" }, actions: [ "find" ] }
Source Database is on a Remote Server If copying from a remote server and the remote server has authentication enabled, you must authenticate to the remote host as a user with the proper authorization. See Authentication
(page 104).
Target Database (todb)
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 system.js
collection in the target database. For example:
{ resource: { db: "myTargetDB", collection: "" }, actions: [ "insert", "createIndex" ] }
{ resource: { db: "myTargetDB", collection: "system.js" }, 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 system.js,
system.users, system.roles, and system.version collections in the target database. For example:
{
{
{
{
{
resource:
resource:
resource:
resource:
resource:
{
{
{
{
{
db:
db:
db:
db:
db:
"myTargetDB",
"myTargetDB",
"myTargetDB",
"myTargetDB",
"myTargetDB",
2.1. mongo Shell Methods
collection:
collection:
collection:
collection:
collection:
"" }, actions: [ "insert", "createIndex" ] },
"system.js" }, actions: [ "insert" ] },
"system.users" }, actions: [ "insert" ] },
"system.roles" }, actions: [ "insert" ] },
"system.version" }, actions: [ "insert" ] }
103
MongoDB Reference Manual, Release 2.8.0-rc3
Authentication If copying from a remote server and the remote server has authentication enabled, then you must
include the <username> and <password>. The method does not transmit the password in plaintext.
Example To copy a database named records into a database named archive_records, use the following
invocation of db.copyDatabase() (page 102):
db.copyDatabase('records', 'archive_records')
See also:
clone (page 320)
db.createCollection()
Definition
db.createCollection(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 db.createCollection() (page 104) method has the following prototype form:
db.createCollection(<name>, { capped: <boolean>,
autoIndexId: <boolean>,
size: <number>,
max: <number>,
storageEngine: <document> } )
The db.createCollection() (page 104) method has the following parameters:
param string name The name of the collection to create.
param document options 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 Enables a capped collection. 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 Specify false to disable the automatic creation of an index on the _id
field. Before 2.2, the default value for autoIndexId was false. See _id Fields and Indexes
on Capped Collections (page 797) for more information.
Do not set autoIndexId to true for replicated collections.
field number size Specifies a maximum size in bytes for a capped collection. The size field is
required for capped collections, and ignored for other collections.
field number max The maximum number of documents allowed in the capped collection. The
size limit takes precedence over this limit. If a capped collection reaches its maximum size
before it reaches the maximum number of documents, MongoDB removes old documents. If
you prefer to use this limit, ensure that the size limit, which is required, is sufficient to contain
the documents limit.
field boolean usePowerOf2Sizes Deprecated since version 2.8: For mmapv1, all collections have
usePowerOf2Sizes (page 322) allocation unless the noPadding option is true.
104
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
field boolean noPadding Changed in version 2.8: For mmapv1, noPadding flag removes all additional space in the record allocation, so that the allocation does not permit documents to grow
after insertion without a new allocation. Defaults to false. Use for insert-only workloads.
field document storageEngine New in version 2.8.
Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection. The value of the storageEngine option should take the following form:e
{ <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 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:
db.createCollection("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 documents.
The following command simply pre-allocates a 2-gigabyte, uncapped collection named people:
db.createCollection("people", { size: 2147483648 } )
This command provides a wrapper around the database command create (page 333).
http://docs.mongodb.org/manual/core/capped-collections for more information
capped collections.
See
about
Specify Storage Engine Options New in version 2.8.
You can specify collection-specific storage engine configuration options when you create a collection with
db.createCollection() (page 104). Consider the following operation:
db.createCollection( "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 options8 for specific
wiredTiger options.
db.currentOp()
Definition
db.currentOp()
Returns a document that contains information on in-progress operations for the database instance.
db.currentOp() (page 105) method has the following form:
8 http://source.wiredtiger.com/2.4.1/struct_w_t___s_e_s_s_i_o_n.html#a358ca4141d59c345f401c58501276bbb
2.1. mongo Shell Methods
105
MongoDB Reference Manual, Release 2.8.0-rc3
db.currentOp(<operations>)
The db.currentOp() (page 105) method can take the following optional argument:
param boolean or document operations 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 document 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 db.currentOp() (page 105), the method returns information on all operations,
including operations on idle connections and system operations.
db.currentOp(true)
Passing in true is equivalent to passing in a query document of { ’$all’:
true }.
If you pass a query document to db.currentOp() (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 you specify in the query document other conditions
as well as ’$all’: true, only the ’$all’: true applies.
Access Control On systems running with authorization, a user must have access that includes the inprog
action. For example, see create-role-to-manage-ops.
Examples The following examples use the db.currentOp() (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:
db.currentOp(
{
"waitingForLock" : true,
$or: [
{ "op" : { "$in" : [ "insert", "update", "remove" ] } },
{ "query.update": { $exists: true } },
{ "query.insert": { $exists: true } },
{ "query.remove": { $exists: true } }
]
}
)
Active Operations with no Yields The following example returns information on all active running operations that
have never yielded:
db.currentOp(
{
"active" : true,
"numYields" : 0,
"waitingForLock" : false
106
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
}
)
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:
db.currentOp(
{
"active" : true,
"secs_running" : { "$gt" : 3 },
"ns" : /^db1./
}
)
Active Indexing Operations The following example returns information on index creation operations:
db.currentOp(
{
$or: [
{ op: "query", "query.createIndexes": { $exists: true } },
{ op: "insert", ns: /\.system\.indexes\b/ }
]
}
)
Output Example The following is an example of db.currentOp() (page 105) output.
{
"inprog": [
{
"opid" : <number>,
"active" : <boolean>,
"secs_running" : <NumberLong()>,
"microsecs_running" : <number>,
"op" : <string>,
"ns" : <string>,
"query" : <document>,
"insert" : <document>,
"planSummary": <string>,
"client" : <string>,
"desc" : <string>,
"threadId" : <string>,
"connectionId" : <number>,
"locks" : {
"^" : <string>,
"^local" : <string>,
"^<database>" : <string>
},
"waitingForLock" : <boolean>,
"msg": <string>,
"progress" : {
"done" : <number>,
"total" : <number>
},
"killPending" : <boolean>,
2.1. mongo Shell Methods
107
MongoDB Reference Manual, Release 2.8.0-rc3
"numYields" : <number>,
"lockStats" : {
"timeLockedMicros" : {
"R" : <NumberLong()>,
"W" : <NumberLong()>,
"r" : <NumberLong()>,
"w" : <NumberLong()>
},
"timeAcquiringMicros" : {
"R" : <NumberLong()>,
"W" : <NumberLong()>,
"r" : <NumberLong()>,
"w" : <NumberLong()>
}
}
},
...
]
}
Output Fields
currentOp.opid
The identifier for the operation. You can pass this value to db.killOp() (page 119) in the mongo (page 610)
shell to terminate the operation.
Warning: Terminate running operations with extreme caution. Only use db.killOp() (page 119) to
terminate operations initiated by clients and do not terminate internal database operations.
currentOp.active
A boolean value specifying whether the operation has started. Value is true if the operation has started or
false if the operation is queued and waiting for a lock to run. active (page 108) may be true even if the
operation has yielded to another operation.
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 108) 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 108) is true).
currentOp.op
A string that identifies the type of operation. The possible values are:
•"none"
•"update"
•"insert"
•"query"
•"getmore"
108
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
•"remove"
•"killcursors"
The "query" type includes operations that use the insert (page 247), update (page 251), and delete
(page 234) commands. Write operations that do not use the aforementioned write commands will show with the
appropriate "insert", "update", or "remove" value.
currentOp.ns
The namespace the operation targets. A namespace consists of the database name and the collection name
concatenated with a dot (.); i.e., "<database>.<collection>".
currentOp.insert
Contains the document to be inserted for operations with op (page 108) value of "insert". Only appears for
operations with op (page 108) value "insert".
Insert operations such as db.collection.insert() (page 55) that use the insert (page 247) command
will have op (page 108) value of "query".
currentOp.query
A document containing information on current operation if op (page 108) value is not "insert". query
(page 109) does not appear for op (page 108) of type "insert".
Write operations that use the insert (page 247), update (page 251), and delete (page 234) commands
have op (page 108) value of "query" and the corresponding query (page 109) contains information on these
operations.
For example, the following query (page 109) field contains information for an update operation:
"query" : {
"update" : "grades",
"updates" : [
{
"q" : {
"x" : {
"$gt" : 70
}
},
"u" : {
"$set" : {
"y" : 1
}
},
"multi" : true,
"upsert" : false
}
],
"ordered" : true
}
The document can be empty for op (page 108) types such as "getmore".
currentOp.planSummary
A string that contains the query plan to help debug slow queries.
currentOp.client
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.
For some commands, including findAndModify (page 239) and db.eval() (page 112), the client will be
0.0.0.0:0, rather than an actual client.
2.1. mongo Shell Methods
109
MongoDB Reference Manual, Release 2.8.0-rc3
currentOp.desc
A description of the client. This string includes the connectionId (page 110).
currentOp.threadId
An identifier for the thread that services the operation and its connection.
currentOp.connectionId
An identifier for the connection where the operation originated.
currentOp.locks
New in version 2.2.
The locks (page 110) document reports by databases the types of locks the operation currently holds. The
possible lock types are:
•R represents the global read lock,
•W represents the global write lock,
•r represents the database specific read lock, and
•w represents the database specific write lock.
currentOp.locks.^
^ (page 110) reports on the use of the global lock for the mongod (page 583) instance. All operations
must hold the global lock for some phases of operation.
currentOp.locks.^local
^local (page 110) reports on the lock for the local database. MongoDB uses the local database
for a number of operations, but the most frequent use of the local database is for the oplog used in
replication.
currentOp.locks.^<database>
locks.^<database> (page 110) reports on the lock state for the database that this operation targets.
currentOp.waitingForLock
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.
currentOp.msg
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.
currentOp.progress
Reports on the progress of mapReduce or indexing operations. The progress (page 110) fields corresponds
to the completion percentage in the msg (page 110) field. The progress (page 110) specifies the following
information:
currentOp.progress.done
Reports the number completed.
currentOp.progress.total
Reports the total number.
currentOp.killPending
Returns true if the operation is currently flagged for termination. When the operation encounters its next safe
termination point, the operation will terminate.
currentOp.numYields
numYields (page 110) is a counter that reports the number of times the operation has yielded to allow other
operations to complete.
110
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
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.
currentOp.lockStats
New in version 2.2.
The lockStats (page 111) document reflects the amount of time the operation has spent both acquiring and
holding locks. lockStats (page 111) reports data on a per-lock type, with the following possible lock types:
•R represents the global read lock,
•W represents the global write lock,
•r represents the database specific read lock, and
•w represents the database specific write lock.
currentOp.timeLockedMicros
The timeLockedMicros (page 111) document reports the amount of time the operation has spent
holding a specific lock.
For operations that require more than one lock, like those that lock the local database to update the
oplog, then the values in this document can be longer than this value may be longer than the total length
of the operation (i.e. secs_running (page 108).)
currentOp.timeLockedMicros.R
Reports the amount of time in microseconds the operation has held the global read lock.
currentOp.timeLockedMicros.W
Reports the amount of time in microseconds the operation has held the global write lock.
currentOp.timeLockedMicros.r
Reports the amount of time in microseconds the operation has held the database specific read lock.
currentOp.timeLockedMicros.w
Reports the amount of time in microseconds the operation has held the database specific write lock.
currentOp.timeAcquiringMicros
The timeAcquiringMicros (page 111) document reports the amount of time the operation has spent
waiting to acquire a specific lock.
currentOp.timeAcquiringMicros.R
Reports the mount of time in microseconds the operation has waited for the global read lock.
currentOp.timeAcquiringMicros.W
Reports the mount of time in microseconds the operation has waited for the global write lock.
currentOp.timeAcquiringMicros.r
Reports the mount of time in microseconds the operation has waited for the database specific read
lock.
currentOp.timeAcquiringMicros.w
Reports the mount of time in microseconds the operation has waited for the database specific write
lock.
db.dropDatabase()
db.dropDatabase()
Removes the current database. Does not change the current database, so the insertion of any documents in this
database will allocate a fresh set of data files.
2.1. mongo Shell Methods
111
MongoDB Reference Manual, Release 2.8.0-rc3
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 266) command in the database you are
deleting.
See also:
dropDatabase (page 334)
db.eval()
Definition
db.eval(function, arguments)
Deprecated since version 2.8.0.
Provides the ability to run JavaScript code on the MongoDB server.
The helper db.eval() (page 112) in the mongo (page 610) shell wraps the eval (page 237) command.
Therefore, the helper method shares the characteristics and behavior of the underlying command with one exception: db.eval() (page 112) method does not support the nolock option.
The method accepts the following parameters:
param JavaScript function function A JavaScript function to execute.
param list arguments 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
Write Lock By default, db.eval() (page 112) takes a global write lock while evaluating the JavaScript function.
As a result, db.eval() (page 112) blocks all other read and write operations to the database while the db.eval()
(page 112) operation runs.
To prevent the taking of the global write lock while evaluating the JavaScript code, use the eval (page 237) command
with nolock set to true. nolock does not impact whether the operations within the JavaScript code take write
locks.
For long running db.eval() (page 112) operation, consider using either the eval command with nolock:
or using other server side code execution options.
true
Sharded Data You can not use db.eval() (page 112) with sharded collections. In general, you should avoid
using db.eval() (page 112) in sharded clusters; nevertheless, it is possible to use db.eval() (page 112) with
non-sharded collections and databases stored in a sharded cluster.
112
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
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 db.eval() (page 112).
Providing such access is not recommended, but if your organization requires a user to run db.eval() (page 112),
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, db.eval() (page 112) executed in a single thread.
Examples The following is an example of the db.eval() (page 112) method:
db.eval( function(name, incAmount) {
var doc = db.myCollection.findOne( { name : name } );
doc = doc || { name : name , num : 0 , total : 0 , avg : 0 };
doc.num++;
doc.total += incAmount;
doc.avg = doc.total / doc.num;
db.myCollection.save( 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 server’s interpreter, you must run db.eval() (page 112). Otherwise, the mongo (page 610)
shell’s JavaScript interpreter evaluates functions entered directly into the shell.
If an error occurs, db.eval() (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:
db.eval( function() { return x + x; }, 3 );
The statement results in the following exception:
{
"errmsg" : "exception: JavaScript execution failed: ReferenceError: x is not defined near '{ retur
"code" : 16722,
"ok" : 0
}
See also:
http://docs.mongodb.org/manual/core/server-side-javascript
db.fsyncLock()
db.fsyncLock()
Forces the mongod (page 583) to flush all pending write operations to the disk and locks the entire mongod
(page 583) instance to prevent additional writes until the user releases the lock with the db.fsyncUnlock()
(page 114) command. db.fsyncLock() (page 113) is an administrative command.
2.1. mongo Shell Methods
113
MongoDB Reference Manual, Release 2.8.0-rc3
This command provides a simple wrapper around a fsync (page 336) database command with the following
syntax:
{ fsync: 1, lock: true }
This function locks the database and create a window for backup operations.
Important: db.fsyncLock() (page 113) may block reads, including those necessary to verify authentication. Such reads are necessary to establish new connections to a mongod (page 583) that enforces authorization
checks.
Warning: When calling db.fsyncLock() (page 113), ensure that the connection is kept open to allow
a subsequent call to db.fsyncUnlock() (page 114).
Closing the connection may make it difficult to release the lock.
db.fsyncUnlock()
db.fsyncUnlock()
Unlocks a mongod (page 583) instance to allow writes and reverses the operation of a db.fsyncLock()
(page 113) operation. Typically you will use db.fsyncUnlock() (page 114) following a database backup
operation.
db.fsyncUnlock() (page 114) is an administrative command.
db.getCollection()
Description
db.getCollection(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 210).
The db.getCollection() (page 114) method has the following parameter:
param string name The name of the collection.
db.getCollectionNames()
Definition
db.getCollectionNames()
Returns An array containing all collections in the existing database.
Considerations Changed in version 2.8.0.
If you use db.getCollectionNames() (page 114) from a version of the mongo (page 610) shell before 2.8.0,
on a mongod (page 583) instance that uses the��wiredTiger�� storage engine, db.getCollectionNames()
(page 114) will return no data, even if there are existing collections.
db.getLastError()
db.getLastError()
Changed in version 2.6: A new protocol for write operations (page 745) integrates write concerns with the write
114
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
operations, eliminating the need for a separate db.getLastError() (page 114) method. Write methods
now return the status of the write operation, including error information.
In previous versions, clients typically used the db.getLastError() (page 114) method in combination with
the write operations to ensure that the write succeeds.
Returns The last error message string.
Sets the level of write concern for confirming the success of write operations.
See
getLastError (page 245) and http://docs.mongodb.org/manual/reference/write-concern
for all options, Write Concern for a conceptual overview, http://docs.mongodb.org/manual/core/write-operati
for information about all write operations in MongoDB.
db.getLastErrorObj()
db.getLastErrorObj()
Changed in version 2.6: A new protocol for write operations (page 745) integrates write concerns with the write
operations, eliminating the need for a separate db.getLastError() (page 114) method. Write methods
now return the status of the write operation, including error information.
In previous versions, clients typically used the db.getLastError() (page 114) method in combination with
the write operations to ensure that the write succeeds.
Returns A full document with status information.
See also:
Write Concern, http://docs.mongodb.org/manual/reference/write-concern,
replica-set-write-concern.
and
db.getLogComponents()
Definition
db.getLogComponents()
New in version 2.8.
Returns the current verbosity settings.
The verbosity settings determine the amount of
http://docs.mongodb.org/manual/reference/log-messages that MongoDB produces
for each log message component.
If a component inherits the verbosity level of its parent, db.getLogComponents() (page 115) displays -1
for the component’s verbosity.
Output The db.getLogComponents() (page 115) returns a document with the verbosity settings. For example:
{
"verbosity" : 0,
"accessControl" : {
"verbosity" : -1
},
"command" : {
"verbosity" : -1
},
"control" : {
2.1. mongo Shell Methods
115
MongoDB Reference Manual, Release 2.8.0-rc3
"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
systemLog.verbosity
and
systemLog.component.<name>.verbosity settings in the configuration file or set the
logComponentVerbosity parameter using the setParameter (page 343) command or use the
db.setLogLevel() (page 124) method. For examples, see log-messages-configure-verbosity.
db.getMongo()
db.getMongo()
Returns The current database connection.
db.getMongo() (page 116) runs when the shell initiates. Use this command to test that the mongo
(page 610) shell has a connection to the proper database instance.
db.getName()
db.getName()
Returns the current database name.
db.getPrevError()
db.getPrevError()
Returns A status document, containing the errors.
116
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Deprecated since version 1.6.
This output reports all errors since the last time the database received a resetError (page 250) (also
db.resetError() (page 123)) command.
This method provides a wrapper around the getPrevError (page 247) command.
db.getProfilingLevel()
db.getProfilingLevel()
This method provides a wrapper around the database command “profile (page 366)” and returns the current
profiling level.
Deprecated since version 1.8.4: Use db.getProfilingStatus() (page 117) for related functionality.
db.getProfilingStatus()
db.getProfilingStatus()
Returns The current profile (page 366) level and slowOpThresholdMs setting.
db.getReplicationInfo()
Definition
db.getReplicationInfo()
Returns A document with the status of the replica status, using data polled from the “oplog”. Use
this output when diagnosing issues with replication.
Output
db.getReplicationInfo.logSizeMB
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.
db.getReplicationInfo.usedMB
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.
db.getReplicationInfo.errmsg
Returns an error message if there are no entries in the oplog.
db.getReplicationInfo.oplogMainRowCount
Only present when there are no entries in the oplog. Reports a the number of items or rows in the oplog (e.g. 0).
db.getReplicationInfo.timeDiff
Returns the difference between the first and last operation in the oplog, represented in seconds.
Only present if there are entries in the oplog.
db.getReplicationInfo.timeDiffHours
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.
db.getReplicationInfo.tFirst
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.
2.1. mongo Shell Methods
117
MongoDB Reference Manual, Release 2.8.0-rc3
Only present if there are entries in the oplog.
db.getReplicationInfo.tLast
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.
db.getReplicationInfo.now
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 you’re connecting from a remote host as a result. Equivalent
to Date() (page 199).
Only present if there are entries in the oplog.
db.getSiblingDB()
Definition
db.getSiblingDB(<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 db.getSiblingDB() (page 118) as an alternative to the use <database> helper. This
is particularly useful when writing scripts using the mongo (page 610) shell where the use helper is not available.
Consider the following sequence of operations:
db = db.getSiblingDB('users')
db.active.count()
This operation sets the db object to point to the database named users, and then returns a count (page 26) of the
collection named active. You can create multiple db objects, that refer to different databases, as in the following
sequence of operations:
users = db.getSiblingDB('users')
records = db.getSiblingDB('records')
users.active.count()
users.active.findOne()
records.requests.count()
records.requests.findOne()
This operation creates two db objects referring to different databases (i.e. users and records) and then returns a
count (page 26) and an example document (page 46) from one collection in that database (i.e. active and requests
respectively.)
db.help()
db.help()
Returns Text output listing common methods on the db object.
118
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.hostInfo()
db.hostInfo()
New in version 2.2.
Returns A document with information about the underlying system that the mongod (page 583) or
mongos (page 601) runs on. Some of the returned fields are only included on some platforms.
db.hostInfo() (page 119) provides a helper in the mongo (page 610) shell around the hostInfo
(page 358) The output of db.hostInfo() (page 119) 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>",
"cpuFeatures" : "<string>",
"pageSize" : <number>,
"numPages" : <number>,
"maxOpenFiles" : <number>
},
"ok" : <return>
}
See hostInfo (page 358) for full documentation of the output of db.hostInfo() (page 119).
db.isMaster()
db.isMaster()
Returns A document that describes the role of the mongod (page 583) instance.
If the mongod (page 583) is a member of a replica set, then the ismaster (page 290) and secondary
(page 290) fields report if the instance is the primary or if it is a secondary member of the replica set.
See
isMaster (page 289) for the complete documentation of the output of db.isMaster() (page 119).
db.killOp()
Description
2.1. mongo Shell Methods
119
MongoDB Reference Manual, Release 2.8.0-rc3
db.killOp(opid)
Terminates an operation as specified by the operation ID. To find operations and their corresponding IDs, see
db.currentOp() (page 105).
The db.killOp() (page 119) method has the following parameter:
param number opid An operation ID.
Warning: Terminate running operations with extreme caution. Only use db.killOp() (page 119) to
terminate operations initiated by clients and do not terminate internal database operations.
db.listCommands()
db.listCommands()
Provides a list of all database commands. See the Database Commands (page 210) document for a more extensive index of these options.
db.loadServerScripts()
db.loadServerScripts()
db.loadServerScripts() (page 120) loads all scripts in the system.js collection for the current
database into the mongo (page 610) shell session.
Documents in the system.js collection have the following prototype form:
{ _id : "<name>" , value : <function> } }
The documents in the system.js collection provide functions that your applications can use in any JavaScript
context with MongoDB in this database. These contexts include $where (page 421) clauses and mapReduce
(page 220) operations.
db.logout()
db.logout()
Ends the current authentication session. This function has no effect if the current session is not authenticated.
Note: If you’re not logged in and using authentication, db.logout() (page 120) 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 db.logout() (page 120) while using the same database context that you
authenticated to.
If you authenticated to a database such as users or $external, you must issue db.logout() (page 120)
against this database in order to successfully log out.
Example
Use the use <database-name> helper in the interactive mongo (page 610) shell, or the following
db.getSiblingDB() (page 118) in the interactive shell or in mongo (page 610) shell scripts to change
the db object:
db = db.getSiblingDB('<database-name>')
120
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
When you have set the database context and db object, you can use the db.logout() (page 120) to log out
of database as in the following operation:
db.logout()
db.logout() (page 120) function provides a wrapper around the database command logout (page 264).
db.printCollectionStats()
db.printCollectionStats()
Provides a wrapper around the db.collection.stats() (page 71) method. Returns statistics from every
collection separated by three hyphen characters.
Note:
The db.printCollectionStats() (page 121) in the mongo (page 610) shell does
not return JSON. Use db.printCollectionStats() (page 121) for manual inspection, and
db.collection.stats() (page 71) in scripts.
See also:
collStats (page 348)
db.printReplicationInfo()
db.printReplicationInfo()
Prints a formatted report of the status of a replica set from the perspective of the primary set member if run on
the primary. 9 The displayed report formats the data returned by db.getReplicationInfo() (page 117).
Note:
The db.printReplicationInfo() (page 121) in the mongo (page 610) shell does
not return JSON. Use db.printReplicationInfo() (page 121) for manual inspection, and
db.getReplicationInfo() (page 117) in scripts.
The output of db.printReplicationInfo()
rs.printReplicationInfo() (page 175).
(page
121)
is
identical
to
that
of
Output Example The following example is a sample output from the db.printReplicationInfo()
(page 121) method run on the primary:
configured oplog size:
log length start to end:
oplog first event time:
oplog last event time:
now:
192MB
65422secs (18.17hrs)
Mon Jun 23 2014 17:47:18 GMT-0400 (EDT)
Tue Jun 24 2014 11:57:40 GMT-0400 (EDT)
Thu Jun 26 2014 14:24:39 GMT-0400 (EDT)
Output Fields db.printReplicationInfo() (page 121) formats and prints the data returned by
db.getReplicationInfo() (page 117):
configured oplog size Displays the db.getReplicationInfo.logSizeMB (page 117) value.
log length start to end Displays
the
db.getReplicationInfo.timeDiff
db.getReplicationInfo.timeDiffHours (page 117) values.
9
If run on a secondary,
the method calls
db.printSlaveReplicationInfo() (page 122) for details.
2.1. mongo Shell Methods
db.printSlaveReplicationInfo()
(page
(page
117)
122).
and
See
121
MongoDB Reference Manual, Release 2.8.0-rc3
oplog first event time Displays the db.getReplicationInfo.tFirst (page 117).
oplog last event time Displays the db.getReplicationInfo.tLast (page 118).
now Displays the db.getReplicationInfo.now (page 118).
See db.getReplicationInfo() (page 117) for description of the data.
db.printShardingStatus()
Definition
db.printShardingStatus()
Prints a formatted report of the sharding configuration and the information regarding existing chunks in a
sharded cluster.
Only use db.printShardingStatus() (page 122) when connected to a mongos (page 601) instance.
The db.printShardingStatus() (page 122) method has the following parameter:
param Boolean verbose If true, the method displays details of the document distribution across
chunks when you have 20 or more chunks.
See sh.status() (page 191) for details of the output.
Note: The db.printShardingStatus() (page 122) in the mongo (page 610) shell does not return JSON. Use db.printShardingStatus() (page 122) for manual inspection, and Config Database
(page 681) in scripts.
See also:
sh.status() (page 191)
db.printSlaveReplicationInfo()
Definition
db.printSlaveReplicationInfo()
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 rs.printSlaveReplicationInfo() (page 176).
Output The following is example output from the rs.printSlaveReplicationInfo() (page 176) method
issued on a replica set with two secondary members:
source: m1.example.net:27017
syncedTo: Thu Apr 10 2014
0 secs (0 hrs) behind the
source: m2.example.net:27017
syncedTo: Thu Apr 10 2014
0 secs (0 hrs) behind the
10:27:47 GMT-0400 (EDT)
primary
10:27:47 GMT-0400 (EDT)
primary
Note: The db.printSlaveReplicationInfo() (page 122) in the mongo (page 610) shell does not return JSON. Use db.printSlaveReplicationInfo() (page 122) for manual inspection, and rs.status()
(page 179) 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 value.
122
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.removeUser()
Deprecated since version 2.6: Use db.dropUser() (page 155) instead of db.removeUser() (page 157)
Definition
db.removeUser(username)
Removes the specified username from the database.
The db.removeUser() (page 157) method has the following parameter:
param string username The database username.
db.repairDatabase()
db.repairDatabase()
db.repairDatabase() (page 123) provides a wrapper around the database command repairDatabase
(page 341), and has the same effect as the run-time option mongod --repair option, limited to only the
current database. See repairDatabase (page 341) for full documentation.
Behavior
Warning: During normal operations, only use the repairDatabase (page 341) command and wrappers
including db.repairDatabase() (page 123) in the mongo (page 610) shell and mongod --repair, to
compact database files and/or reclaim disk space. Be aware that these operations remove and do not save any
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 341).
When using journaling, there is almost never any need to run repairDatabase (page 341). 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 db.repairDatabase() (page 123) is now available for secondary as well as primary
members of replica sets.
db.resetError()
db.resetError()
Deprecated since version 1.6.
Resets the error message returned by db.getPrevError (page 116) or getPrevError (page 247). Provides a wrapper around the resetError (page 250) command.
db.runCommand()
Definition
db.runCommand(command)
Provides a helper to run specified database commands (page 210). 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, db.runCommand() (page 123) transforms the string into a
document.”
2.1. mongo Shell Methods
123
MongoDB Reference Manual, Release 2.8.0-rc3
New
in
version
2.6:
To
specify
a
time
limit
in
milliseconds,
http://docs.mongodb.org/manual/tutorial/terminate-running-operations.
see
Behavior db.runCommand() (page 123) runs the command in the context of the current database. Some commands are only applicable in the context of the admin database, and you must change your db object to before
running these commands.
db.serverBuildInfo()
db.serverBuildInfo()
Provides a wrapper around the buildInfo (page 346) database command. buildInfo (page 346) returns a
document that contains an overview of parameters used to compile this mongod (page 583) instance.
db.serverCmdLineOpts()
db.serverCmdLineOpts()
Wraps the getCmdLineOpts (page 357) database command.
Returns a document that reports on the arguments and configuration options used to start the mongod (page 583)
or mongos (page 601) instance.
See http://docs.mongodb.org/manual/reference/configuration-options, mongod
(page 583), and mongos (page 600) for additional information on available MongoDB runtime options.
db.serverStatus()
db.serverStatus()
Returns a document that provides an overview of the database process’s state.
This command provides a wrapper around the database command serverStatus (page 366).
Changed in version 2.4: In 2.4 you can dynamically suppress portions of the db.serverStatus()
(page 124) output, or include suppressed sections in a document passed to the db.serverStatus()
(page 124) method, as in the following example:
db.serverStatus( { repl: 0, indexCounters: 0, locks: 0 } )
db.serverStatus( { workingSet: 1, metrics: 0, locks: 0 } )
db.serverStatus() (page 124) includes all fields by default, except workingSet (page 381)
rangeDeleter (page 377), and some content in the repl (page 374) document.
Note: You may only dynamically include top-level fields from the serverStatus (page 366) document that are
not included by default. You can exclude any field that db.serverStatus() (page 124) includes by default.
See also:
serverStatus (page 366) for complete documentation of the output of this function.
db.setLogLevel()
Definition
124
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.setLogLevel()
New in version 2.8.
Sets a single verbosity level for log messages.
db.setLogLevel() (page 124) has the following form:
db.setLogLevel(<level>, <component>)
db.setLogLevel() (page 124) takes the following parameters:
param int level The log verbosity level.
The verbosity level can range from 0 to 5:
• 0 is the MongoDB’s default log verbosity level, to include Informational messages.
• 1 to 5 increases the verbosity level to include Debug messages.
To inherit the verbosity level of the component’s parent, you can also specify -1.
param string component The name of the component for which to specify the log verbosity level. The component name corresponds to the <name> from the corresponding
systemLog.component.<name>.verbosity setting:
• accessControl
• command
• control
• geo
• index
• network
• query
• replication
• sharding
• storage
• storage.journal
• write
Omit to specify the default verbosity level for all components.
Behavior db.setLogLevel() (page 124) sets a single verbosity level. To set multiple verbosity levels in a single
operation, use either the setParameter (page 343) command to set the logComponentVerbosity parameter.
You can also specify the verbosity settings in the configuration file. See log-messages-configure-verbosity
for examples.
Examples
Set Default Verbosity Level Omit the <component> parameter to set the default verbosity for all components;
i.e. the systemLog.verbosity setting. The operation sets the default verbosity to 1:
db.setLogLevel(1)
2.1. mongo Shell Methods
125
MongoDB Reference Manual, Release 2.8.0-rc3
Set Verbosity Level for a Component Specify the <component> parameter to set the verbosity for the component. The following operation updates the systemLog.component.storage.journal.verbosity to
2:
db.setLogLevel(2, "storage.journal" )
db.setProfilingLevel()
Definition
db.setProfilingLevel(level, slowms)
Modifies the current database profiler level used by the database profiling system to capture data about performance. The method provides a wrapper around the database command profile (page 366).
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 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 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 583) writes the output of the database profiler to the system.profile collection.
mongod (page 583) prints information about queries that take longer than the slowOpThresholdMs to the
log even when the database profiler is not active.
db.shutdownServer()
db.shutdownServer()
Shuts down the current mongod (page 583) or mongos (page 601) 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 344).
db.stats()
Description
db.stats(scale)
Returns statistics that reflect the use state of a single database.
The db.stats() (page 126) method has the following parameter:
param number scale The scale at which to deliver results. Unless specified, this command returns
all data in bytes.
Returns A document with statistics reflecting the database system’s state. For an explanation of the
output, see dbStats (page 352).
The db.stats() (page 126) method is a wrapper around the dbStats (page 352) database command.
126
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Example The following example converts the returned values to kilobytes:
db.stats(1024)
Note: The scale factor rounds values to whole numbers. This can produce unpredictable and unexpected results in
some situations.
db.upgradeCheck()
Definition
db.upgradeCheck(<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 610)
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 749),
•documents with illegal field names (page 698),
•collections without an _id index, and
•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 Document to limit the scope of the check to the specified collection 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 749) for details.
See also:
db.upgradeCheckAllDBs() (page 128)
Behavior db.upgradeCheck() (page 127) 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 601).
• For replica sets, run the command on the secondary members.
db.upgradeCheck() (page 127) can miss new data during the check when run on a live system with active write
operations.
For index validation, db.upgradeCheck() (page 127) only supports the check of version 1 indexes and skips the
check of version 0 indexes.
The db.upgradeCheck() (page 127) checks all of the data stored in the mongod (page 583) instance: the time to
run db.upgradeCheck() (page 127) depends on the quantity of data stored by mongod (page 583).
2.1. mongo Shell Methods
127
MongoDB Reference Manual, Release 2.8.0-rc3
Required Access On systems running with authorization, a user must have access that includes the find
action on all collections, including the system collections (page 688).
Example The following example connects to a secondary running on localhost and runs
db.upgradeCheck() (page 127) 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 "db.getMongo().setSlaveOk(); db.upgradeCheck( { collection: 'employees' } )"
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.
db.upgradeCheckAllDBs()
Definition
db.upgradeCheckAllDBs()
New in version 2.6.
Performs a preliminary check for upgrade preparedness to 2.6. The helper, available in the 2.6 mongo (page 610)
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 749),
128
Chapter 2. Interfaces Reference
localhos
MongoDB Reference Manual, Release 2.8.0-rc3
•documents with illegal field names (page 698),
•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 749) for details.
See also:
db.upgradeCheck() (page 127)
Behavior db.upgradeCheckAllDBs() (page 128) 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 601).
• For replica sets, run the command on the secondary members.
db.upgradeCheckAllDBs() (page 128) can miss new data during the check when run on a live system with
active write operations.
For index validation, db.upgradeCheckAllDBs() (page 128) only supports the check of version 1 indexes and
skips the check of version 0 indexes.
The db.upgradeCheckAllDBs() (page 128) checks all of the data stored in the mongod (page 583) instance:
the time to run db.upgradeCheckAllDBs() (page 128) depends on the quantity of data stored by mongod
(page 583).
Required Access On systems running with authorization, 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 688).
You must run the db.upgradeCheckAllDBs() (page 128) operation in the admin database.
Example The following example connects to a secondary running on localhost and runs
db.upgradeCheckAllDBs() (page 128) against the admin database. Because the output from the method can
be quite large, the example pipes the output to a file.
./mongo --eval "db.getMongo().setSlaveOk(); db.upgradeCheckAllDBs();" 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.
2.1. mongo Shell Methods
129
MongoDB Reference Manual, Release 2.8.0-rc3
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.
db.version()
db.version()
Returns The version of the mongod (page 583) or mongos (page 601) instance.
2.1.4 Query Plan Cache
Query Plan Cache Methods
The PlanCache methods are only accessible from a collection’s plan cache object. To retrieve the plan cache object,
use the db.collection.getPlanCache() (page 134) method.
Name
PlanCache.clear()
(page 130)
Description
Clears all the cached query plans for a collection. Accessible through the plan
cache object of a specific collection, i.e.
db.collection.getPlanCache().clear().
PlanCache.clearPlansByQuery()
Clears the cached query plans for the specified query shape. Accessible through the
(page 131)
plan cache object of a specific collection, i.e.
db.collection.getPlanCache().clearPlansByQuery()
PlanCache.getPlansByQuery()
Displays the cached query plans for the specified query shape. Accessible through
(page 132)
the plan cache object of a specific collection, i.e.
db.collection.getPlanCache().getPlansByQuery().
PlanCache.help()
Displays the methods available for a collection’s query plan cache. Accessible
(page 133)
through the plan cache object of a specific collection, i.e.
db.collection.getPlanCache().help().
PlanCache.listQueryShapes()
Displays the query shapes for which cached query plans exist. Accessible through
(page 133)
the plan cache object of a specific collection, i.e.
db.collection.getPlanCache().listQueryShapes().
db.collection.getPlanCache()
Returns an interface to access the query plan cache object and associated PlanCache
(page 134)
methods for a collection.”
PlanCache.clear()
Definition
130
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
PlanCache.clear()
Removes all cached query plans for a collection.
The method is only available from the plan cache object (page 134) of a specific collection; i.e.
db.collection.getPlanCache().clear()
For example, to clear the cache for the orders collection:
db.orders.getPlanCache().clear()
Required Access On systems running with authorization, a user must have access that includes the
planCacheWrite action.
See also:
• db.collection.getPlanCache() (page 134)
• PlanCache.clearPlansByQuery() (page 131)
PlanCache.clearPlansByQuery()
Definition
PlanCache.clearPlansByQuery(<query>, <projection>, <sort>)
Clears the cached query plans for the specified query shape.
The method is only available from the plan cache object (page 134) of a specific collection; i.e.
db.collection.getPlanCache().clearPlansByQuery( <query>, <projection>, <sort> )
The PlanCache.clearPlansByQuery() (page 131) 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 The projection associated with the query shape. Required if specifying the sort parameter.
param document sort The sort associated with the query shape.
To see the query shapes for which cached query plans exist, use the PlanCache.listQueryShapes()
(page 133) method.
Required Access On systems running with authorization, a user must have access that includes the
planCacheWrite action.
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:
2.1. mongo Shell Methods
131
MongoDB Reference Manual, Release 2.8.0-rc3
db.orders.getPlanCache().clearPlansByQuery(
{ "qty" : { "$gt" : 10 } },
{ },
{ "ord_date" : 1 }
)
See also:
• db.collection.getPlanCache() (page 134)
• PlanCache.listQueryShapes() (page 133)
• PlanCache.clear() (page 130)
PlanCache.getPlansByQuery()
Definition
PlanCache.getPlansByQuery(<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 134) of a specific collection; i.e.
db.collection.getPlanCache().getPlansByQuery( <query>, <projection>, <sort> )
The PlanCache.getPlansByQuery() (page 132) 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 The projection associated with the query shape. Required if specifying the sort parameter.
param document sort The sort associated with the query shape.
Returns Array of cached query plans for a query shape.
To see the query shapes for which cached query plans exist, use the PlanCache.listQueryShapes()
(page 133) method.
Required Access On systems running with authorization, 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:
132
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.orders.getPlanCache().getPlansByQuery(
{ "qty" : { "$gt" : 10 } },
{ },
{ "ord_date" : 1 }
)
See also:
• db.collection.getPlanCache() (page 134)
• PlanCache.listQueryShapes() (page 133)
• PlanCache.help() (page 133)
PlanCache.help()
Definition
PlanCache.help()
Displays the methods available to view and modify a collection’s query plan cache.
The method is only available from the plan cache object (page 134) of a specific collection; i.e.
db.collection.getPlanCache().help()
See also:
db.collection.getPlanCache() (page 134)
PlanCache.listQueryShapes()
Definition
PlanCache.listQueryShapes()
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 134) of a specific collection; i.e.
db.collection.getPlanCache().listQueryShapes()
Returns Array of query shape documents.
The method wraps the planCacheListQueryShapes (page 260) command.
Required Access On systems running with authorization, 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:
db.orders.getPlanCache().listQueryShapes()
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:
2.1. mongo Shell Methods
133
MongoDB Reference Manual, Release 2.8.0-rc3
[
{
"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:
• db.collection.getPlanCache() (page 134)
• PlanCache.getPlansByQuery() (page 132)
• PlanCache.help() (page 133)
• planCacheListQueryShapes (page 260)
db.collection.getPlanCache()
Definition
db.collection.getPlanCache()
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:
134
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Name
PlanCache.help()
(page 133)
Description
Displays the methods available for a collection’s query plan cache. Accessible
through the plan cache object of a specific collection, i.e.
db.collection.getPlanCache().help().
PlanCache.listQueryShapes()
Displays the query shapes for which cached query plans exist. Accessible through
(page 133)
the plan cache object of a specific collection, i.e.
db.collection.getPlanCache().listQueryShapes().
PlanCache.getPlansByQuery()
Displays the cached query plans for the specified query shape. Accessible through
(page 132)
the plan cache object of a specific collection, i.e.
db.collection.getPlanCache().getPlansByQuery().
PlanCache.clearPlansByQuery()
Clears the cached query plans for the specified query shape. Accessible through the
(page 131)
plan cache object of a specific collection, i.e.
db.collection.getPlanCache().clearPlansByQuery()
PlanCache.clear()
Clears all the cached query plans for a collection. Accessible through the plan
(page 130)
cache object of a specific collection, i.e.
db.collection.getPlanCache().clear().
2.1.5 Bulk Write Operation
Bulk Operation Methods
New in version 2.6.
Name
Bulk() (page 135)
Bulk.execute() (page 137)
Bulk.find() (page 139)
Bulk.find.remove() (page 140)
Bulk.find.removeOne()
(page 140)
Bulk.find.replaceOne()
(page 141)
Bulk.find.update() (page 142)
Bulk.find.updateOne()
(page 142)
Bulk.find.upsert() (page 144)
Bulk.getOperations()
(page 147)
Bulk.insert() (page 148)
Bulk.toString() (page 148)
Bulk.tojson() (page 149)
Description
Bulk operations builder.
Executes a list of operations in bulk.
Specifies the query condition for an update or a remove operation.
Adds a multiple document remove operation to a list of operations.
Adds a single document remove operation to a list of operations.
Adds a single document replacement operation to a list of operations.
Adds a multi update operation to a list of operations.
Adds a single document update operation to a list of operations.
Specifies upsert: true for an update operation.
Returns an array of write operations executed in the Bulk()
(page 135) operations object.
Adds an insert operation to a list of operations.
Returns the Bulk.tojson() (page 149) results as a string.
Returns a JSON document that contains the number of operations and
batches in the Bulk() (page 135) operations object.
db.collection.initializeOrderedBulkOp()
Initializes a Bulk() (page 135) operations builder for an ordered list
(page 149)
of operations.
db.collection.initializeUnorderedBulkOp()
Initializes a Bulk() (page 135) operations builder for an unordered
(page 150)
list of operations.
Bulk()
Description
Bulk()
New in version 2.6.
2.1. mongo Shell Methods
135
MongoDB Reference Manual, Release 2.8.0-rc3
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 db.collection.initializeOrderedBulkOp() (page 149)
or the db.collection.initializeUnorderedBulkOp() (page 150) 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 db.collection.initializeOrderedBulkOp() (page 149) to create a builder for an ordered list of
write commands.
When executing an ordered (page 149) list of operations, MongoDB groups the operations by the operation
type (page 148) 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 697). If a group exceeds this limit
(page 697), MongoDB will divide the group into smaller groups of 1000 or less. For example, if the bulk operations 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 Bulk.getOperations() (page 147)
after the execution.
Executing an ordered (page 149) list of operations on a sharded collection will generally be slower than executing
an unordered (page 150) 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 nondeterministic 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 db.collection.initializeUnorderedBulkOp() (page 150) to create a builder for an unordered list
of write commands.
When executing an unordered (page 150) 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 150) bulk operations.
Each group of operations can have at most 1000 operations (page 697). If a group exceeds this limit
(page 697), MongoDB will divide the group into smaller groups of 1000 or less. For example, if the bulk operations 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 Bulk.getOperations() (page 147)
after the execution.
Methods The Bulk() (page 135) builder has the following methods:
136
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Name
Description
Bulk.insert()
Adds an insert operation to a list of operations.
(page 148)
Bulk.find() (page 139)
Specifies the query condition for an update or a remove operation.
Bulk.find.removeOne() Adds a single document remove operation to a list of operations.
(page 140)
Bulk.find.remove()
Adds a multiple document remove operation to a list of operations.
(page 140)
Bulk.find.replaceOne()Adds a single document replacement operation to a list of operations.
(page 141)
Bulk.find.updateOne() Adds a single document update operation to a list of operations.
(page 142)
Bulk.find.update()
Adds a multi update operation to a list of operations.
(page 142)
Bulk.find.upsert()
Specifies upsert: true for an update operation.
(page 144)
Bulk.execute()
Executes a list of operations in bulk.
(page 137)
Bulk.getOperations() Returns an array of write operations executed in the Bulk() (page 135)
(page 147)
operations object.
Bulk.tojson()
Returns a JSON document that contains the number of operations and batches in
(page 149)
the Bulk() (page 135) operations object.
Bulk.toString()
Returns the Bulk.tojson() (page 149) results as a string.
(page 148)
Bulk.execute()
Description
Bulk.execute()
New in version 2.6.
Executes the list of operations built by the Bulk() (page 135) operations builder.
Bulk.execute() (page 137) accepts the following parameter:
param document writeConcern Write concern document for the bulk operation as a whole.
Omit to use default. For a standalone mongod (page 583) server, the write concern defaults to
{ w: 1 }. With a replica set, the default write concern is { w: 1 } unless modified as
part of the replica set configuration.
See Override Default Write Concern (page 138) for an example.
Returns A BulkWriteResult (page 198) object that contains the status of the operation.
After execution, you cannot re-execute the Bulk() (page 135) object without reinitializing.
See db.collection.initializeUnorderedBulkOp() (page 150) and
db.collection.initializeOrderedBulkOp() (page 149).
Behavior
Ordered Operations When executing an ordered (page 149) list of operations, MongoDB groups the operations
by the operation type (page 148) 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
2.1. mongo Shell Methods
137
MongoDB Reference Manual, Release 2.8.0-rc3
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 697). If a group exceeds this limit
(page 697), MongoDB will divide the group into smaller groups of 1000 or less. For example, if the bulk operations 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 Bulk.getOperations() (page 147)
after the execution.
Executing an ordered (page 149) list of operations on a sharded collection will generally be slower than executing
an unordered (page 150) list since with an ordered list, each operation must wait for the previous operation to finish.
Unordered Operations When executing an unordered (page 150) 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 150) bulk operations.
Each group of operations can have at most 1000 operations (page 697). If a group exceeds this limit
(page 697), MongoDB will divide the group into smaller groups of 1000 or less. For example, if the bulk operations 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 Bulk.getOperations() (page 147)
after the execution.
Examples
Execute Bulk Operations The following initializes a Bulk() (page 135) operations builder on the items collection, adds a series of insert operations, and executes the operations:
var bulk = db.items.initializeUnorderedBulkOp();
bulk.insert( { item: "abc123", status: "A", defaultQty: 500, points: 5 } );
bulk.insert( { item: "ijk123", status: "A", defaultQty: 100, points: 10 } );
bulk.execute( );
The operation returns the following BulkWriteResult() (page 198) object:
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
For details on the return object, see BulkWriteResult() (page 198). For details on the batches executed, see
Bulk.getOperations() (page 147).
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 writes propagate to a
majority of the replica set members or the method times out after 5 seconds.
138
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
var bulk = db.items.initializeUnorderedBulkOp();
bulk.insert( { item: "efg123", status: "A", defaultQty: 100, points: 0 } );
bulk.insert( { item: "xyz123", status: "A", defaultQty: 100, points: 0 } );
bulk.execute( { w: "majority", wtimeout: 5000 } );
The operation returns the following BulkWriteResult() (page 198) object:
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
See
Bulk() (page 135) for a listing of methods available for bulk operations.
Bulk.find()
Description
Bulk.find(<query>)
New in version 2.6.
Specifies a query condition for an update or a remove operation.
Bulk.find() (page 139) accepts the following parameter:
param document query Specifies a query condition using Query Selectors (page 400) to select documents 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 692).
With remove operations, the query document must be less than or equal to the maximum BSON
document size (page 692).
Use Bulk.find() (page 139) with the following write operations:
•Bulk.find.removeOne() (page 140)
•Bulk.find.remove() (page 140)
•Bulk.find.replaceOne() (page 141)
•Bulk.find.updateOne() (page 142)
•Bulk.find.update() (page 142)
Example The following example initializes a Bulk() (page 135) 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 Bulk.find() (page 139) method to specify a condition for their respective actions:
2.1. mongo Shell Methods
139
MongoDB Reference Manual, Release 2.8.0-rc3
var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "D" } ).remove();
bulk.find( { status: "P" } ).update( { $set: { points: 0 } } )
bulk.execute();
See also:
• db.collection.initializeUnorderedBulkOp() (page 150)
• db.collection.initializeOrderedBulkOp() (page 149)
• Bulk.execute() (page 137)
Bulk.find.remove()
Description
Bulk.find.remove()
New in version 2.6.
Adds a remove operation to a bulk operations list. Use the Bulk.find() (page 139) method to specify the condition that determines which documents to remove. The Bulk.find.remove() (page 140)
method removes all matching documents in the collection. To limit the remove to a single document, see
Bulk.find.removeOne() (page 140).
Example The following example initializes a Bulk() (page 135) 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 = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "D" } ).remove();
bulk.execute();
See also:
• db.collection.initializeUnorderedBulkOp() (page 150)
• db.collection.initializeOrderedBulkOp() (page 149)
• Bulk.find() (page 139)
• Bulk.find.removeOne() (page 140)
• Bulk.execute() (page 137)
Bulk.find.removeOne()
Description
Bulk.find.removeOne()
New in version 2.6.
Adds a single document remove operation to a bulk operations list. Use the Bulk.find() (page 139)
method to specify the condition that determines which document to remove. The Bulk.find.removeOne()
(page 140) limits the removal to one document. To remove multiple documents, see Bulk.find.remove()
(page 140).
140
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Example The following example initializes a Bulk() (page 135) operations builder for the items collection and
adds two Bulk.find.removeOne() (page 140) 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 = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "D" } ).removeOne();
bulk.find( { status: "P" } ).removeOne();
bulk.execute();
See also:
• db.collection.initializeUnorderedBulkOp() (page 150)
• db.collection.initializeOrderedBulkOp() (page 149)
• Bulk.find() (page 139)
• Bulk.find.remove() (page 140)
• Bulk.execute() (page 137)
• All Bulk Methods (page 136)
Bulk.find.replaceOne()
Description
Bulk.find.replaceOne(<document>)
New in version 2.6.
Adds a single document replacement operation to a bulk operations list. Use the Bulk.find()
(page 139) method to specify the condition that determines which document to replace.
The
Bulk.find.replaceOne() (page 141) method limits the replacement to a single document.
Bulk.find.replaceOne() (page 141) accepts the following parameter:
param document replacement A replacement document that completely replaces the existing document. Contains only field and value pairs.
The sum of the associated <query> document from the Bulk.find() (page 139) and the
replacement document must be less than or equal to the maximum BSON document size
(page 692).
To specify an upsert for this operation, see Bulk.find.upsert() (page 144).
Example The following example initializes a Bulk() (page 135) operations builder for the items collection, and
adds various replaceOne (page 141) operations to the list of operations.
var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { item: "abc123" } ).replaceOne( { item: "abc123", status: "P", points: 100 } );
bulk.execute();
See also:
• db.collection.initializeUnorderedBulkOp() (page 150)
• db.collection.initializeOrderedBulkOp() (page 149)
• Bulk.find() (page 139)
• Bulk.execute() (page 137)
2.1. mongo Shell Methods
141
MongoDB Reference Manual, Release 2.8.0-rc3
• All Bulk Methods (page 136)
Bulk.find.update()
Description
Bulk.find.update(<update>)
New in version 2.6.
Adds a multi update operation to a bulk operations list. The method updates specific fields in existing documents.
Use the Bulk.find() (page 139) method to specify the condition that determines which documents to update. The Bulk.find.update() (page 142) method updates all matching documents. To specify a single
document update, see Bulk.find.updateOne() (page 142).
Bulk.find.update() (page 142) accepts the following parameter:
param document update Specifies the fields to update. Only contains update operator (page 451)
expressions.
The sum of the associated <query> document from the Bulk.find() (page 139) and
the update document must be less than or equal to the maximum BSON document size
(page 692).
To specify upsert: true for this operation, see Bulk.find.upsert() (page 144).
With
Bulk.find.upsert() (page 144), if no documents match the Bulk.find() (page 139) query condition, the update operation inserts only a single document.
Example The following example initializes a Bulk() (page 135) operations builder for the items collection, and
adds various multi update operations to the list of operations.
var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "D" } ).update( { $set: { status: "I", points: "0" } } );
bulk.find( { item: null } ).update( { $set: { item: "TBD" } } );
bulk.execute();
See also:
• db.collection.initializeUnorderedBulkOp() (page 150)
• db.collection.initializeOrderedBulkOp() (page 149)
• Bulk.find() (page 139)
• Bulk.find.updateOne() (page 142)
• Bulk.execute() (page 137)
• All Bulk Methods (page 136)
Bulk.find.updateOne()
Description
Bulk.find.updateOne(<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.
142
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Use the Bulk.find() (page 139) method to specify the condition that determines which document to update.
The Bulk.find.updateOne() (page 142) method limits the update or replacement to a single document.
To update multiple documents, see Bulk.find.update() (page 142).
Bulk.find.updateOne() (page 142) accepts the following parameter:
param document update An update document that updates specific fields or a replacement document that completely replaces the existing document.
An update document only contains update operator (page 451) expressions. A replacement
document contains only field and value pairs.
The sum of the associated <query> document from the Bulk.find() (page 139) 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 Bulk.find.upsert() (page 144).
Behavior
Update Specific Fields If the <update> document contains only update operator (page 451) expressions, as in:
{
$set: { status: "D" },
points: { $inc: 2 }
}
Then, Bulk.find.updateOne() (page 142) 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"
}
Then, Bulk.find.updateOne() (page 142) replaces the matching document with the <update> document
with the exception of the _id field. The Bulk.find.updateOne() (page 142) method does not replace the _id
value.
Example The following example initializes a Bulk() (page 135) operations builder for the items collection, and
adds various updateOne (page 142) operations to the list of operations.
var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "D" } ).updateOne( { $set: { status: "I", points: "0" } } );
bulk.find( { item: null } ).updateOne(
{
item: "TBD",
points: 0,
inStock: true,
status: "I"
}
);
bulk.execute();
2.1. mongo Shell Methods
143
MongoDB Reference Manual, Release 2.8.0-rc3
See also:
• db.collection.initializeUnorderedBulkOp() (page 150)
• db.collection.initializeOrderedBulkOp() (page 149)
• Bulk.find() (page 139)
• Bulk.find.update() (page 142)
• Bulk.execute() (page 137)
• All Bulk Methods (page 136)
Bulk.find.upsert()
Description
Bulk.find.upsert()
New in version 2.6.
Sets the upsert option to true for an update or a replacement operation and has the following syntax:
Bulk.find(<query>).upsert().update(<update>);
Bulk.find(<query>).upsert().updateOne(<update>);
Bulk.find(<query>).upsert().replaceOne(<replacement>);
With the upsert option set to true, if no matching documents exist for the Bulk.find() (page 139)
condition, then the update or the replacement operation performs an insert. If a matching document does exist,
then the update or replacement operation performs the specified update or replacement.
Use Bulk.find.upsert() (page 144) with the following write operations:
•Bulk.find.replaceOne() (page 141)
•Bulk.find.updateOne() (page 142)
•Bulk.find.update() (page 142)
Behavior The following describe the insert behavior of various write operations when used in conjunction with
Bulk.find.upsert() (page 144).
Insert for Bulk.find.replaceOne() The Bulk.find.replaceOne() (page 141) method accepts, as its
parameter, a replacement document that only contains field and value pairs:
var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { item: "abc123" } ).upsert().replaceOne(
{
item: "abc123",
status: "P",
points: 100,
}
);
bulk.execute();
If the replacement operation with the Bulk.find.upsert() (page 144) option performs an insert, the inserted
document is the replacement document. If the replacement document does not specify an _id field, MongoDB adds
the _id field:
144
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
{
"_id" : ObjectId("52ded3b398ca567f5c97ac9e"),
"item" : "abc123",
"status" : "P",
"points" : 100
}
Insert for Bulk.find.updateOne() The Bulk.find.updateOne() (page 142) method accepts, as its
parameter, an <update> document that contains only field and value pairs or only update operator (page 451)
expressions.
Field and Value Pairs If the <update> document contains only field and value pairs:
var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "P" } ).upsert().updateOne(
{
item: "TBD",
points: 0,
inStock: true,
status: "I"
}
);
bulk.execute();
Then, if the update operation with the Bulk.find.upsert() (page 144) option performs an insert, the inserted
document is the <update> document. If the update document does not specify an _id field, MongoDB adds the
_id field:
{
"_id" : ObjectId("52ded5a898ca567f5c97ac9f"),
"item" : "TBD",
"points" : 0,
"inStock" : true,
"status" : "I"
}
Update Operator Expressions
expressions:
If the <update> document contains contains only update operator (page 451)
var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "P", item: null } ).upsert().updateOne(
{
$setOnInsert: { defaultQty: 0, inStock: true },
$currentDate: { lastModified: true },
$set: { points: "0" }
}
);
bulk.execute();
Then, if the update operation with the Bulk.find.upsert() (page 144) option performs an insert, the update
operation inserts a document with field and values from the <query> document of the Bulk.find() (page 139)
method and then applies the specified update from the <update> document:
{
"_id" : ObjectId("52ded68c98ca567f5c97aca0"),
2.1. mongo Shell Methods
145
MongoDB Reference Manual, Release 2.8.0-rc3
"item" : null,
"status" : "P",
"defaultQty" : 0,
"inStock" : true,
"lastModified" : ISODate("2014-01-21T20:20:28.786Z"),
"points" : "0"
}
If neither the <query> document nor the <update> document specifies an _id field, MongoDB adds the _id
field.
Insert for Bulk.find.update() When using upsert() (page 144) with the multiple document update
method Bulk.find.update() (page 142), if no documents match the query condition, the update operation inserts a single document.
The Bulk.find.update() (page 142) method accepts, as its parameter, an <update> document that contains
only update operator (page 451) expressions:
var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "P" } ).upsert().update(
{
$setOnInsert: { defaultQty: 0, inStock: true },
$currentDate: { lastModified: true },
$set: { status: "I", points: "0" }
}
);
bulk.execute();
Then, if the update operation with the Bulk.find.upsert() (page 144) option performs an insert, the update
operation inserts a single document with the fields and values from the <query> document of the Bulk.find()
(page 139) method and then applies the specified update from the <update> document:
{
"_id": ObjectId("52ded81a98ca567f5c97aca1"),
"status": "I",
"defaultQty": 0,
"inStock": true,
"lastModified": ISODate("2014-01-21T20:27:06.691Z"),
"points": "0"
}
If neither the <query> document nor the <update> document specifies an _id field, MongoDB adds the _id
field.
See also:
• db.collection.initializeUnorderedBulkOp() (page 150)
• db.collection.initializeOrderedBulkOp() (page 149)
• Bulk.find() (page 139)
• Bulk.execute() (page 137)
• All Bulk Methods (page 136)
146
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Bulk.getOperations()
Bulk.getOperations()
New in version 2.6.
Returns an array of write operations executed through Bulk.execute() (page 137). The returned write
operations are in groups as determined by MongoDB for execution. For information on how MongoDB groups
the list of bulk write operations, see Bulk.execute() Behavior (page 137).
Only use Bulk.getOperations() (page 147) after a Bulk.execute() (page 137). Calling
Bulk.getOperations() (page 147) before you call Bulk.execute() (page 137) will result in an incomplete list.
Example The following initializes a Bulk() (page 135) operations builder on the items collection, adds a series
of write operations, executes the operations, and then calls getOperations() (page 147) on the bulk builder
object:
var bulk = db.items.initializeUnorderedBulkOp();
for (var i = 1; i <= 1500; i++) {
bulk.insert( { x: i } );
}
bulk.execute();
bulk.getOperations();
The getOperations() (page 147) method returns an array with the operations executed. The output shows that
MongoDB divided the operations into 2 groups, one with 1000 operations and one with 500. For information on how
MongoDB groups the list of bulk write operations, see Bulk.execute() Behavior (page 137)
Although the method returns all 1500 operations in the returned array, this page omits some of the results for brevity.
[
{
"originalZeroIndex" : 0,
"batchType" : 1,
"operations" : [
{ "_id" : ObjectId("53a8959f1990ca24d01c6165"), "x" : 1 },
... // Content omitted for brevity
{ "_id" : ObjectId("53a8959f1990ca24d01c654c"), "x" : 1000 }
]
},
{
"originalZeroIndex" : 1000,
"batchType" : 1,
"operations" : [
{ "_id" : ObjectId("53a8959f1990ca24d01c654d"), "x" : 1001 },
... // Content omitted for brevity
{ "_id" : ObjectId("53a8959f1990ca24d01c6740"), "x" : 1500 }
]
}
]
2.1. mongo Shell Methods
147
MongoDB Reference Manual, Release 2.8.0-rc3
Returned Fields The array contains documents with the following fields:
originalZeroIndex
Specifies the order in which the operation was added to the bulk operations builder, based on a zero index; e.g.
first operation added to the bulk operations builder will have originalZeroIndex (page 148) value of 0.
batchType
Specifies the write operations type.
batchType
1
2
3
Operation
Insert
Update
Remove
operations
Array of documents that contain the details of the operation.
See also:
Bulk() (page 135) and Bulk.execute() (page 137).
Bulk.insert()
Description
Bulk.insert(<document>)
New in version 2.6.
Adds an insert operation to a bulk operations list.
Bulk.insert() (page 148) 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 692).
Example The following initializes a Bulk() (page 135) operations builder for the items collection and adds a
series of insert operations to add multiple documents:
var bulk = db.items.initializeUnorderedBulkOp();
bulk.insert( { item: "abc123", defaultQty: 100, status: "A", points: 100 } );
bulk.insert( { item: "ijk123", defaultQty: 200, status: "A", points: 200 } );
bulk.insert( { item: "mop123", defaultQty: 0, status: "P", points: 0 } );
bulk.execute();
See also:
• db.collection.initializeUnorderedBulkOp() (page 150)
• db.collection.initializeOrderedBulkOp() (page 149)
• Bulk.execute() (page 137)
Bulk.toString()
Bulk.toString()
New in version 2.6.
Returns as a string a JSON document that contains the number of operations and batches in the Bulk()
(page 135) object.
148
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Example The following initializes a Bulk() (page 135) operations builder on the items collection, adds a series
of write operations, and calls Bulk.toString() (page 148) on the bulk builder object.
var bulk = db.items.initializeOrderedBulkOp();
bulk.insert( { item: "abc123", status: "A", defaultQty: 500, points: 5 } );
bulk.insert( { item: "ijk123", status: "A", defaultQty: 100, points: 10 } );
bulk.find( { status: "D" } ).removeOne();
bulk.toString();
The Bulk.toString() (page 148) returns the following JSON document
{ “nInsertOps” : 2, “nUpdateOps” : 0, “nRemoveOps” : 1, “nBatches” : 2 }
See also:
Bulk() (page 135)
Bulk.tojson()
Bulk.tojson()
New in version 2.6.
Returns a JSON document that contains the number of operations and batches in the Bulk() (page 135) object.
Example The following initializes a Bulk() (page 135) operations builder on the items collection, adds a series
of write operations, and calls Bulk.tojson() (page 149) on the bulk builder object.
var bulk = db.items.initializeOrderedBulkOp();
bulk.insert( { item: "abc123", status: "A", defaultQty: 500, points: 5 } );
bulk.insert( { item: "ijk123", status: "A", defaultQty: 100, points: 10 } );
bulk.find( { status: "D" } ).removeOne();
bulk.tojson();
The Bulk.tojson() (page 149) returns the following JSON document
{ “nInsertOps” : 2, “nUpdateOps” : 0, “nRemoveOps” : 1, “nBatches” : 2 }
See also:
Bulk() (page 135)
db.collection.initializeOrderedBulkOp()
Definition
db.collection.initializeOrderedBulkOp()
Initializes and returns a new Bulk() (page 135) operations builder for a collection. The builder constructs an
ordered list of write operations that MongoDB executes in bulk.
Returns new Bulk() (page 135) operations builder object.
Behavior
Order of Operation With an ordered operations list, MongoDB executes the write operations in the list serially.
2.1. mongo Shell Methods
149
MongoDB Reference Manual, Release 2.8.0-rc3
Execution of Operations When executing an ordered (page 149) list of operations, MongoDB groups the operations by the operation type (page 148) 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 697). If a group exceeds this limit
(page 697), MongoDB will divide the group into smaller groups of 1000 or less. For example, if the bulk operations 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 Bulk.getOperations() (page 147)
after the execution.
Executing an ordered (page 149) list of operations on a sharded collection will generally be slower than executing
an unordered (page 150) 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 135) operations builder on the users collection, adds a series
of write operations, and executes the operations:
var bulk = db.users.initializeOrderedBulkOp();
bulk.insert( { user: "abc123", status: "A", points: 0 }
bulk.insert( { user: "ijk123", status: "A", points: 0 }
bulk.insert( { user: "mop123", status: "P", points: 0 }
bulk.find( { status: "D" } ).remove();
bulk.find( { status: "P" } ).update( { $set: { comment:
bulk.execute();
);
);
);
"Pending" } } );
See also:
• db.collection.initializeUnorderedBulkOp() (page 150)
• Bulk.find() (page 139)
• Bulk.find.removeOne() (page 140)
• Bulk.execute() (page 137)
db.collection.initializeUnorderedBulkOp()
Definition
db.collection.initializeUnorderedBulkOp()
New in version 2.6.
Initializes and returns a new Bulk() (page 135) operations builder for a collection. The builder constructs an
unordered list of write operations that MongoDB executes in bulk.
Behavior
150
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
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 db.collection.initializeOrderedBulkOp()
(page 149) instead.
Execution of Operations When executing an unordered (page 150) 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 150) bulk operations.
Each group of operations can have at most 1000 operations (page 697). If a group exceeds this limit
(page 697), MongoDB will divide the group into smaller groups of 1000 or less. For example, if the bulk operations 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 Bulk.getOperations() (page 147)
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 135) operations builder and adds a series of insert operations to
add multiple documents:
var bulk = db.users.initializeUnorderedBulkOp();
bulk.insert( { user: "abc123", status: "A", points: 0 } );
bulk.insert( { user: "ijk123", status: "A", points: 0 } );
bulk.insert( { user: "mop123", status: "P", points: 0 } );
bulk.execute();
See also:
• db.collection.initializeOrderedBulkOp() (page 149)
• Bulk() (page 135)
• Bulk.insert() (page 148)
• Bulk.execute() (page 137)
2.1.6 User Management
User Management Methods
Name
db.changeUserPassword() (page 152)
db.createUser() (page 152)
db.dropAllUsers() (page 154)
db.dropUser() (page 155)
db.getUser() (page 155)
db.getUsers() (page 156)
db.grantRolesToUser() (page 156)
db.removeUser() (page 157)
db.revokeRolesFromUser() (page 157)
db.updateUser() (page 159)
2.1. mongo Shell Methods
Description
Changes an existing user’s password.
Creates a new user.
Deletes all users associated with a database.
Removes a single user.
Returns information about the specified user.
Returns information about all users associated with a database.
Grants a role and its privileges to a user.
Deprecated. Removes a user from a database.
Removes a role from a user.
Updates user data.
151
MongoDB Reference Manual, Release 2.8.0-rc3
db.changeUserPassword()
Definition
db.changeUserPassword(username, password)
Updates a user’s password.
param string username Specifies an existing username with access privileges for this database.
param string password Specifies the corresponding password.
param string mechanism Specifies the authentication mechanism used.
Defaults to
MONGODB-CR. PLAIN is used for SASL/LDAP authentication, available only in
MongoDB Enterprise.
Example The following operation changes the reporting user’s password to SOh3TbYhx8ypJPxmt1oOfL:
db.changeUserPassword("reporting", "SOh3TbYhx8ypJPxmt1oOfL")
db.createUser()
Definition
db.createUser(user, writeConcern)
Creates a new user for the database where the method runs. db.createUser() (page 152) returns a duplicate
user error if the user already exists on the database.
The db.createUser() (page 152) method has the following syntax:
field document user The document with authentication and access information about the user to
create.
field document writeConcern The level of write concern for the creation operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
The user document defines the user and has the following form:
{ user: "<name>",
pwd: "<cleartext password>",
customData: { <any information> },
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
]
}
The user document has the following fields:
field string user The name of the new user.
field string pwd The user’s password.
The pwd field is not required if you run
db.createUser() (page 152) on the $external database to create users who have credentials stored externally to MongoDB.
any document customData Any arbitrary information. This field can be used to store any data an
admin wishes to associate with this particular user. For example, this could be the user’s full
name or employee id.
field array roles The roles granted to the user. Can specify an empty array [] to create users without
roles.
152
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where db.createUser() (page 152) runs, you can either
specify the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
The db.createUser() (page 152) method wraps the createUser (page 265) command.
Behavior
Encryption db.createUser() (page 152) sends password to the MongoDB instance without encryption. To
encrypt the password during transmission, use SSL.
External Credentials Users created on the $external database should have credentials stored externally to MongoDB, as, for example, with MongoDB Enterprise installations that use Kerberos.
local Database You cannot create users on the local database.
Required Access You must have the createUser action on a database to create a new user on that database.
You must have the grantRole action on a role’s database to grant the role to another user.
If you have the userAdmin or userAdminAnyDatabase role, you have those actions.
Examples The following db.createUser() (page 152) operation creates the accountAdmin01 user on the
products database.
use products
db.createUser( { "user" : "accountAdmin01",
"pwd": "cleartext password",
"customData" : { employeeId: 12345 },
"roles" : [ { role: "clusterAdmin", db: "admin" },
{ role: "readAnyDatabase", db: "admin" },
"readWrite"
] },
{ w: "majority" , wtimeout: 5000 } )
The operation gives accountAdmin01 the following roles:
• the clusterAdmin and readAnyDatabase roles on the admin database
• the readWrite role on the products database
Create User with Roles The following operation creates accountUser in the products database and gives the
user the readWrite and dbAdmin roles.
2.1. mongo Shell Methods
153
MongoDB Reference Manual, Release 2.8.0-rc3
use products
db.createUser(
{
user: "accountUser",
pwd: "password",
roles: [ "readWrite", "dbAdmin" ]
}
)
Create User Without Roles The following operation creates a user named reportsUser in the admin database
but does not yet assign roles:
use admin
db.createUser(
{
user: "reportsUser",
pwd: "password",
roles: [ ]
}
)
Create Administrative User with Roles The following operation creates a user named appAdmin in the admin
database and gives the user readWrite access to the config database, which lets the user change certain settings
for sharded clusters, such as to the balancer setting.
use admin
db.createUser(
{
user: "appAdmin",
pwd: "password",
roles:
[
{ role: "readWrite", db: "config" },
"clusterAdmin"
]
}
)
db.dropAllUsers()
Definition
db.dropAllUsers(writeConcern)
Removes all users from the current database.
Warning: The dropAllUsers method removes all users from the database.
The dropAllUsers method takes the following arguments:
field document writeConcern The level of write concern for the removal operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
The db.dropAllUsers() (page 154) method wraps the dropAllUsersFromDatabase (page 266)
command.
154
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Required Access You must have the dropUser action on a database to drop a user from that database.
Example The following db.dropAllUsers() (page 154) operation drops every user from the products
database.
use products
db.dropAllUsers( {w: "majority", wtimeout: 5000} )
The n field in the results document shows the number of users removed:
{ "n" : 12, "ok" : 1 }
db.dropUser()
Definition
db.dropUser(username, writeConcern)
Removes the user from the current database.
The db.dropUser() (page 155) method takes the following arguments:
param string username The name of the user to remove from the database.
field document writeConcern The level of write concern for the removal operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
The db.dropUser() (page 155) method wraps the dropUser (page 267) command.
Required Access You must have the dropUser action on a database to drop a user from that database.
Example The following db.dropUser() (page 155) operation drops the accountAdmin01 user on the
products database.
use products
db.dropUser("accountAdmin01", {w: "majority", wtimeout: 5000})
db.getUser()
Definition
db.getUser(username)
Returns user information for a specified user. Run this method on the user’s database. The user must exist on
the database on which the method runs.
The db.getUser() (page 155) method has the following parameter:
param string username The name of the user for which to retrieve information.
db.getUser() (page 155) wraps the usersInfo (page 272) command.
Required Access
tials.
You must have the viewUser action on another user’s database to view the other user’s creden-
You can view your own information.
2.1. mongo Shell Methods
155
MongoDB Reference Manual, Release 2.8.0-rc3
Example The following sequence of operations returns information about the appClient user on the accounts
database:
use accounts
db.getUser("appClient")
db.getUsers()
Definition
db.getUsers()
Returns information for all the users in the database.
db.getUsers() (page 156) wraps the usersInfo (page 272) command.
Required Access
tials.
You must have the viewUser action on another user’s database to view the other user’s creden-
You can view your own information.
db.grantRolesToUser()
Definition
db.grantRolesToUser(username, roles, writeConcern)
Grants additional roles to a user.
The grantRolesToUser method uses the following syntax:
db.grantRolesToUser( "<username>", [ <roles> ], { <writeConcern> } )
The grantRolesToUser method takes the following arguments:
param string user The name of the user to whom to grant roles.
field array roles An array of additional roles to grant to the user.
field document writeConcern The level of write concern for the modification.
The
writeConcern document takes the same fields as the getLastError (page 245) command.
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where db.grantRolesToUser() (page 156) runs, you
can either specify the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
The db.grantRolesToUser() (page 156) method wraps the grantRolesToUser (page 267) command.
Required Access You must have the grantRole action on a database to grant a role on that database.
156
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Example Given a user accountUser01 in the products database with the following roles:
"roles" : [
{ "role" : "assetsReader",
"db" : "assets"
}
]
The following grantRolesToUser() operation gives accountUser01 the readWrite role on the
products database and the read role on the stock database.
use products
db.grantRolesToUser(
"accountUser01",
[ "readWrite" , { role: "read", db: "stock" } ],
{ w: "majority" , wtimeout: 4000 }
)
The user accountUser01 in the products database now has the following roles:
"roles" : [
{ "role"
"db" :
},
{ "role"
"db" :
},
{ "role"
"db" :
}
]
: "assetsReader",
"assets"
: "read",
"stock"
: "readWrite",
"products"
db.removeUser()
Deprecated since version 2.6: Use db.dropUser() (page 155) instead of db.removeUser() (page 157)
Definition
db.removeUser(username)
Removes the specified username from the database.
The db.removeUser() (page 157) method has the following parameter:
param string username The database username.
db.revokeRolesFromUser()
Definition
db.revokeRolesFromUser()
Removes a one or more roles from a user on the current database. The db.revokeRolesFromUser()
(page 157) method uses the following syntax:
db.revokeRolesFromUser( "<username>", [ <roles> ], { <writeConcern> } )
The revokeRolesFromUser method takes the following arguments:
param string user The name of the user from whom to revoke roles.
2.1. mongo Shell Methods
157
MongoDB Reference Manual, Release 2.8.0-rc3
field array roles The roles to remove from the user.
field document writeConcern The level of write concern for the modification.
The
writeConcern document takes the same fields as the getLastError (page 245) command.
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where db.revokeRolesFromUser() (page 157) runs,
you can either specify the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
The db.revokeRolesFromUser() (page 157) method wraps the revokeRolesFromUser (page 269)
command.
Required Access You must have the revokeRole action on a database to revoke a role on that database.
Example The accountUser01 user in the products database has the following roles:
"roles" : [
{ "role"
"db" :
},
{ "role"
"db" :
},
{ "role"
"db" :
}
]
: "assetsReader",
"assets"
: "read",
"stock"
: "readWrite",
"products"
The following db.revokeRolesFromUser() (page 157) method removes the two of the user’s roles: the read
role on the stock database and the readWrite role on the products database, which is also the database on
which the method runs:
use products
db.revokeRolesFromUser( "accountUser01",
[ { role: "read", db: "stock" }, "readWrite" ],
{ w: "majority" }
)
The user accountUser01 user in the products database now has only one remaining role:
"roles" : [
{ "role" : "assetsReader",
"db" : "assets"
}
]
db.updateUser()
158
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Definition
db.updateUser(username, update, writeConcern)
Updates the user’s profile on the database on which you run the method. An update to a field completely
replaces the previous field’s values. This includes updates to the user’s roles array.
Warning: When you update the roles array, you completely replace the previous array’s values. To
add or remove roles without replacing all the user’s existing roles, use the db.grantRolesToUser()
(page 156) or db.revokeRolesFromUser() (page 157) methods.
The db.updateUser() (page 159) method uses the following syntax:
db.updateUser(
"<username>",
{
customData : { <any information> },
roles : [
{ role: "<role>", db: "<database>" } | "<role>",
...
],
pwd: "<cleartext password>"
},
writeConcern: { <write concern> }
)
The db.updateUser() (page 159) method has the following arguments.
param string username The name of the user to update.
param document update A document containing the replacement data for the user. This data completely replaces the corresponding data for the user.
field document writeConcern The level of write concern for the update operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
The update document specifies the fields to update and their new values. All fields in the update document
are optional, but must include at least one field.
The update document has the following fields:
field document customData Any arbitrary information.
field array roles The roles granted to the user. An update to the roles array overrides the previous
array’s values.
field string pwd The user’s password.
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where db.updateUser() (page 159) runs, you can either
specify the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
The db.updateUser() (page 159) method wraps the updateUser (page 270) command.
2.1. mongo Shell Methods
159
MongoDB Reference Manual, Release 2.8.0-rc3
Behavior db.updateUser() (page 159) sends password to the MongoDB instance without encryption. To encrypt the password during transmission, use SSL.
Required Access You must have access that includes the revokeRole action on all databases in order to update a
user’s roles array.
You must have the grantRole action on a role’s database to add a role to a user.
To change another user’s pwd or customData field, you must have the changeAnyPassword and
changeAnyCustomData actions respectively on that user’s database.
To modify your own password and custom data, you must have privileges that grant changeOwnPassword and
changeOwnCustomData actions respectively on the user’s database.
Example Given a user appClient01 in the products database with the following user info:
{
"_id" : "products.appClient01",
"user" : "appClient01",
"db" : "products",
"customData" : { "empID" : "12345", "badge" : "9156" },
"roles" : [
{ "role" : "readWrite",
"db" : "products"
},
{ "role" : "read",
"db" : "inventory"
}
]
}
The following db.updateUser() (page 159) method completely replaces the user’s customData and roles
data:
use products
db.updateUser( "appClient01",
{
customData : { employeeId : "0x3039" },
roles : [
{ role : "read", db : "assets"
]
}
)
}
The user appClient01 in the products database now has the following user information:
{
"_id" : "products.appClient01",
"user" : "appClient01",
"db" : "products",
"customData" : { "employeeId" : "0x3039" },
"roles" : [
{ "role" : "read",
"db" : "assets"
}
]
}
160
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
2.1.7 Role Management
Role Management Methods
Name
db.createRole() (page 161)
db.dropAllRoles() (page 162)
db.dropRole() (page 163)
db.getRole() (page 163)
db.getRoles() (page 164)
db.grantPrivilegesToRole() (page 165)
db.grantRolesToRole() (page 166)
db.revokePrivilegesFromRole()
(page 167)
db.revokeRolesFromRole() (page 169)
db.updateRole() (page 170)
Description
Creates a role and specifies its privileges.
Deletes all user-defined roles associated with a database.
Deletes a user-defined role.
Returns information for the specified role.
Returns information for all the user-defined roles in a
database.
Assigns privileges to a user-defined role.
Specifies roles from which a user-defined role inherits
privileges.
Removes the specified privileges from a user-defined role.
Removes a role from a user.
Updates a user-defined role.
db.createRole()
Definition
db.createRole(role, writeConcern)
Creates a role and specifies its privileges. The role applies to the database on which you run the method. The
db.createRole() (page 161) method returns a duplicate role error if the role already exists in the database.
The db.createRole() (page 161) method takes the following arguments:
param document role A document containing the name of the role and the role definition.
field document writeConcern The level of write concern to apply to this operation. The
writeConcern document uses the same fields as the getLastError (page 245) command.
The role document has the following form:
{ role: "<name>",
privileges: [
{ resource: { <resource> }, actions: [ "<action>", ... ] },
...
],
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
]
}
The role document has the following fields:
field string role The name of the new role.
field array privileges The privileges to grant the role. A privilege consists of a resource and permitted actions. You must specify the privileges field. Use an empty array to specify no
privileges. For the syntax of a privilege, see the privileges array.
field array roles An array of roles from which this role inherits privileges. You must specify the
roles field. Use an empty array to specify no roles.
2.1. mongo Shell Methods
161
MongoDB Reference Manual, Release 2.8.0-rc3
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where db.createRole() (page 161) runs, you can either
specify the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
The db.createRole() (page 161) method wraps the createRole (page 274) command.
Behavior A role’s privileges apply to the database where the role is created. The role can inherit privileges from
other roles in its database. A role created on the admin database can include privileges that apply to all databases or
to the cluster and can inherit privileges from roles in other databases.
Required Access To create a role in a database, the user must have:
• the createRole action on that database resource.
• the grantRole action on that database to specify privileges for the new role as well as to specify roles to
inherit from.
Built-in roles userAdmin and userAdminAnyDatabase provide createRole and grantRole actions on
their respective resources.
Example The following db.createRole() (page 161) method creates the myClusterwideAdmin role on
the admin database:
use admin
db.createRole({ role: "myClusterwideAdmin",
privileges: [
{ resource: { cluster: true }, actions: [ "addShard" ] },
{ resource: { db: "config", collection: "" }, actions: [ "find", "update", "insert", "remove" ] }
{ resource: { db: "users", collection: "usersCollection" }, actions: [ "update", "insert", "remov
{ resource: { db: "", collection: "" }, actions: [ "find" ] }
],
roles: [
{ role: "read", db: "admin" }
],
writeConcern: { w: "majority" , wtimeout: 5000 }
})
db.dropAllRoles()
Definition
db.dropAllRoles(writeConcern)
Deletes all user-defined roles on the database where you run the method.
Warning: The dropAllRoles method removes all user-defined roles from the database.
The dropAllRoles method takes the following argument:
162
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
field document writeConcern The level of write concern for the removal operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
Returns The number of user-defined roles dropped.
The db.dropAllRoles() (page 162) method wraps the dropAllRolesFromDatabase (page 275)
command.
Required Access You must have the dropRole action on a database to drop a role from that database.
Example The following operations drop all user-defined roles from the products database and uses a write concern of majority.
use products
db.dropAllRoles( { w: "majority" } )
The method returns the number of roles dropped:
4
db.dropRole()
Definition
db.dropRole(rolename, writeConcern)
Deletes a user-defined role from the database on which you run the method.
The db.dropRole() (page 163) method takes the following arguments:
param string rolename The name of the user-defined role to remove from the database.
field document writeConcern The level of write concern for the removal operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
The db.dropRole() (page 163) method wraps the dropRole (page 276) command.
Required Access You must have the dropRole action on a database to drop a role from that database.
Example The following operations remove the readPrices role from the products database:
use products
db.dropRole( "readPrices", { w: "majority" } )
db.getRole()
Definition
db.getRole(rolename, showPrivileges)
Returns the roles from which this role inherits privileges. Optionally, the method can also return all the role’s
privileges.
Run db.getRole() (page 163) from the database that contains the role. The command can retrieve information for both user-defined roles and built-in roles.
2.1. mongo Shell Methods
163
MongoDB Reference Manual, Release 2.8.0-rc3
The db.getRole() (page 163) method takes the following arguments:
param string rolename The name of the role.
param document showPrivileges If true, returns the role’s privileges. Pass this argument as a
document: {showPrivileges: true}.
db.getRole() (page 163) wraps the rolesInfo (page 283) command.
Required Access To view a role’s information, you must be explicitly granted the role or must have the viewRole
action on the role’s database.
Examples The following operation returns role inheritance information for the role associate defined on the
products database:
use products
db.getRole( "associate" )
The following operation returns role inheritance information and privileges for the role associate defined on the
products database:
use products
db.getRole( "associate", { showPrivileges: true } )
db.getRoles()
Definition
db.getRoles()
Returns information for all the roles in the database on which the command runs. The method can be run with
or without an argument.
If run without an argument, db.getRoles() (page 164) returns inheritance information for the database’s
user-defined roles.
To return more information, pass the db.getRoles() (page 164) a document with the following fields:
field integer rolesInfo Set this field to 1 to retrieve all user-defined roles.
field Boolean showBuiltinRoles Set to true to display built-in roles as well as user-defined roles.
field Boolean showPrivileges Set the field to true to show role privileges, including both privileges inherited from other roles and privileges defined directly. By default, the command returns
only the roles from which this role inherits privileges and does not return specific privileges.
db.getRoles() (page 164) wraps the rolesInfo (page 283) command.
Required Access To view a role’s information, you must be explicitly granted the role or must have the viewRole
action on the role’s database.
Example The following operations return documents for all the roles on the products database, including role
privileges and built-in roles:
db.getRoles(
{
rolesInfo: 1,
showPrivileges:true,
164
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
showBuiltinRoles: true
}
)
db.grantPrivilegesToRole()
Definition
db.grantPrivilegesToRole(rolename, privileges, writeConcern)
Grants additional privileges to a user-defined role.
The grantPrivilegesToRole() method uses the following syntax:
db.grantPrivilegesToRole(
"< rolename >",
[
{ resource: { <resource> }, actions: [ "<action>", ... ] },
...
],
{ < writeConcern > }
)
The grantPrivilegesToRole() method takes the following arguments:
param string rolename The name of the role to grant privileges to.
field array privileges The privileges to add to the role.
privileges.
For the format of a privilege, see
field document writeConcern The level of write concern for the modification.
The
writeConcern document takes the same fields as the getLastError (page 245) command.
The grantPrivilegesToRole() method can grant one or more privileges. Each <privilege> has the
following syntax:
{ resource: { <resource> }, actions: [ "<action>", ... ] }
The db.grantPrivilegesToRole() (page 165) method wraps the grantPrivilegesToRole
(page 277) command.
Behavior A role’s privileges apply to the database where the role is created. A role created on the admin database
can include privileges that apply to all databases or to the cluster.
Required Access You must have the grantRole action on the database a privilege targets in order to grant the
privilege. To grant a privilege on multiple databases or on the cluster resource, you must have the grantRole
action on the admin database.
Example The following db.grantPrivilegesToRole() (page 165) operation grants two additional privileges to the role inventoryCntrl01, which exists on the products database. The operation is run on that
database:
use products
db.grantPrivilegesToRole(
"inventoryCntrl01",
[
2.1. mongo Shell Methods
165
MongoDB Reference Manual, Release 2.8.0-rc3
{
resource: { db: "products", collection: "" },
actions: [ "insert" ]
},
{
resource: { db: "products", collection: "system.indexes" },
actions: [ "find" ]
}
],
{ w: "majority" }
)
The first privilege permits users with this role to perform the insert action on all collections of the products
database, except the system collections (page 688). To access a system collection, a privilege must explicitly specify
the system collection in the resource document, as in the second privilege.
The second privilege permits users with this role to perform the find action on the product database’s system
collection named system.indexes (page 689).
db.grantRolesToRole()
Definition
db.grantRolesToRole(rolename, roles, writeConcern)
Grants roles to a user-defined role.
The grantRolesToRole method uses the following syntax:
db.grantRolesToRole( "<rolename>", [ <roles> ], { <writeConcern> } )
The grantRolesToRole method takes the following arguments:
param string rolename The name of the role to which to grant sub roles.
field array roles An array of roles from which to inherit.
field document writeConcern The level of write concern for the modification.
The
writeConcern document takes the same fields as the getLastError (page 245) command.
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where db.grantRolesToRole() (page 166) runs, you
can either specify the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
The db.grantRolesToRole() (page 166) method wraps the grantRolesToRole (page 278) command.
Behavior A role can inherit privileges from other roles in its database. A role created on the admin database can
inherit privileges from roles in any database.
Required Access You must have the grantRole action on a database to grant a role on that database.
166
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Example The following grantRolesToRole() operation updates the productsReaderWriter role in the
products database to inherit the privileges of productsReader role:
use products
db.grantRolesToRole(
"productsReaderWriter",
[ "productsReader" ],
{ w: "majority" , wtimeout: 5000 }
)
db.revokePrivilegesFromRole()
Definition
db.revokePrivilegesFromRole(rolename, privileges, writeConcern)
Removes the specified privileges from the user-defined role on the database where the method runs. The
revokePrivilegesFromRole method has the following syntax:
db.revokePrivilegesFromRole(
"<rolename>",
[
{ resource: { <resource> }, actions: [ "<action>", ... ] },
...
],
{ <writeConcern> }
)
The revokePrivilegesFromRole method takes the following arguments:
param string rolename The name of the user-defined role from which to revoke privileges.
field array privileges An array of privileges to remove from the role. See privileges for more
information on the format of the privileges.
field document writeConcern The level of write concern for the modification.
The
writeConcern document takes the same fields as the getLastError (page 245) command.
The
db.revokePrivilegesFromRole()
(page
revokePrivilegesFromRole (page 279) command.
167)
method
wraps
the
Behavior To revoke a privilege, the resource document pattern must match exactly the resource field of
that privilege. The actions field can be a subset or match exactly.
For example, given the role accountRole in the products database with the following privilege that specifies the
products database as the resource:
{
"resource" : {
"db" : "products",
"collection" : ""
},
"actions" : [
"find",
"update"
]
}
2.1. mongo Shell Methods
167
MongoDB Reference Manual, Release 2.8.0-rc3
You cannot revoke find and/or update from just one collection in the products database. The following operations result in no change to the role:
use products
db.revokePrivilegesFromRole(
"accountRole",
[
{
resource : {
db : "products",
collection : "gadgets"
},
actions : [
"find",
"update"
]
}
]
)
db.revokePrivilegesFromRole(
"accountRole",
[
{
resource : {
db : "products",
collection : "gadgets"
},
actions : [
"find"
]
}
]
)
To revoke the "find" and/or the "update" action from the role accountRole, you must match the resource
document exactly. For example, the following operation revokes just the "find" action from the existing privilege.
use products
db.revokePrivilegesFromRole(
"accountRole",
[
{
resource : {
db : "products",
collection : ""
},
actions : [
"find"
]
}
]
)
Required Access You must have the revokeRole action on the database a privilege targets in order to revoke
that privilege. If the privilege targets multiple databases or the cluster resource, you must have the revokeRole
action on the admin database.
168
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Example The following operation removes multiple privileges from the associates role:
db.revokePrivilegesFromRole(
"associate",
[
{
resource: { db: "products", collection: "" },
actions: [ "createCollection", "createIndex", "find" ]
},
{
resource: { db: "products", collection: "orders" },
actions: [ "insert" ]
}
],
{ w: "majority" }
)
db.revokeRolesFromRole()
Definition
db.revokeRolesFromRole(rolename, roles, writeConcern)
Removes the specified inherited roles from a role.
The revokeRolesFromRole method uses the following syntax:
db.revokeRolesFromRole( "<rolename>", [ <roles> ], { <writeConcern> } )
The revokeRolesFromRole method takes the following arguments:
param string rolename The name of the role from which to revoke roles.
field array roles The inherited roles to remove.
field document writeConcern The level of write concern to apply to this operation. The
writeConcern document uses the same fields as the getLastError (page 245) command.
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where db.revokeRolesFromRole() (page 169) runs,
you can either specify the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
The db.revokeRolesFromRole() (page 169) method wraps the revokeRolesFromRole (page 282)
command.
Required Access You must have the revokeRole action on a database to revoke a role on that database.
Example The purchaseAgents role in the emea database inherits privileges from several other roles, as listed
in the roles array:
2.1. mongo Shell Methods
169
MongoDB Reference Manual, Release 2.8.0-rc3
{
"_id" : "emea.purchaseAgents",
"role" : "purchaseAgents",
"db" : "emea",
"privileges" : [],
"roles" : [
{
"role" : "readOrdersCollection",
"db" : "emea"
},
{
"role" : "readAccountsCollection",
"db" : "emea"
},
{
"role" : "writeOrdersCollection",
"db" : "emea"
}
]
}
The following db.revokeRolesFromRole() (page 169) operation on the emea database removes two roles
from the purchaseAgents role:
use emea
db.revokeRolesFromRole( "purchaseAgents",
[
"writeOrdersCollection",
"readOrdersCollection"
],
{ w: "majority" , wtimeout: 5000 }
)
The purchaseAgents role now contains just one role:
{
"_id" : "emea.purchaseAgents",
"role" : "purchaseAgents",
"db" : "emea",
"privileges" : [],
"roles" : [
{
"role" : "readAccountsCollection",
"db" : "emea"
}
]
}
db.updateRole()
Definition
db.updateRole(rolename, update, writeConcern)
Updates a user-defined role. The db.updateRole() (page 170) method must run on the role’s database.
An update to a field completely replaces the previous field’s values. To grant or remove roles or privileges
without replacing all values, use one or more of the following methods:
•db.grantRolesToRole() (page 166)
170
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
•db.grantPrivilegesToRole() (page 165)
•db.revokeRolesFromRole() (page 169)
•db.revokePrivilegesFromRole() (page 167)
Warning: An update to the privileges or roles array completely replaces the previous array’s values.
The updateRole() method uses the following syntax:
db.updateRole(
"<rolename>",
{
privileges:
[
{ resource: { <resource> }, actions: [ "<action>", ... ] },
...
],
roles:
[
{ role: "<role>", db: "<database>" } | "<role>",
...
]
},
{ <writeConcern> }
)
The db.updateRole() (page 170) method takes the following arguments.
param string rolename The name of the user-defined role to update.
param document update A document containing the replacement data for the role. This data completely replaces the corresponding data for the role.
field document writeConcern The level of write concern for the update operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
The update document specifies the fields to update and the new values. Each field in the update document
is optional, but the document must include at least one field. The update document has the following fields:
field array privileges Required if you do not specify roles array. The privileges to grant the role.
An update to the privileges array overrides the previous array’s values. For the syntax for
specifying a privilege, see the privileges array.
field array roles Required if you do not specify privileges array. The roles from which this
role inherits privileges. An update to the roles array overrides the previous array’s values.
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where db.updateRole() (page 170) runs, you can either
specify the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
The db.updateRole() (page 170) method wraps the updateRole (page 286) command.
2.1. mongo Shell Methods
171
MongoDB Reference Manual, Release 2.8.0-rc3
Behavior A role’s privileges apply to the database where the role is created. The role can inherit privileges from
other roles in its database. A role created on the admin database can include privileges that apply to all databases or
to the cluster and can inherit privileges from roles in other databases.
Required Access You must have the revokeRole action on all databases in order to update a role.
You must have the grantRole action on the database of each role in the roles array to update the array.
You must have the grantRole action on the database of each privilege in the privileges array to update the
array. If a privilege’s resource spans databases, you must have grantRole on the admin database. A privilege
spans databases if the privilege is any of the following:
• a collection in all databases
• all collections and all database
• the cluster resource
Example The following db.updateRole() (page 170) method replaces the privileges and the roles for
the inventoryControl role that exists in the products database. The method runs on the database that contains
inventoryControl:
use products
db.updateRole(
"inventoryControl",
{
privileges:
[
{
resource: { db:"products", collection:"clothing" },
actions: [ "update", "createCollection", "createIndex"]
}
],
roles:
[
{
role: "read",
db: "products"
}
]
},
{ w:"majority" }
)
To view a role’s privileges, use the rolesInfo (page 283) command.
172
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
2.1.8 Replication
Replication Methods
Name
Description
rs.add() (page 173)
Adds a member to a replica set.
rs.addArb() (page 174) Adds an arbiter to a replica set.
rs.conf() (page 174)
Returns the replica set configuration document.
rs.freeze() (page 175) Prevents the current member from seeking election as primary for a period of time.
rs.help() (page 175)
Returns basic help text for replica set functions.
rs.initiate()
Initializes a new replica set.
(page 175)
rs.printReplicationInfo()
Prints a report of the status of the replica set from the perspective of the primary.
(page 175)
rs.printSlaveReplicationInfo()
Prints a report of the status of the replica set from the perspective of the
(page 176)
secondaries.
rs.reconfig()
Re-configures a replica set by applying a new replica set configuration object.
(page 176)
rs.remove() (page 178) Remove a member from a replica set.
rs.slaveOk()
Sets the slaveOk property for the current connection. Deprecated. Use
(page 178)
readPref() (page 93) and Mongo.setReadPref() (page 204) to set read
preference.
rs.status() (page 179) Returns a document with information about the state of the replica set.
rs.stepDown()
Causes the current primary to become a secondary which forces an election.
(page 179)
rs.syncFrom()
Sets the member that this replica set member will sync from, overriding the default
(page 179)
sync target selection logic.
rs.add()
Definition
rs.add()
Adds a member to a replica set. To run the method, you must connect to the primary of the replica set.
param string,document host The new member to add to the replica set.
If a string, specify the hostname and optionally the port number for the new member. See Pass
a Hostname String to rs.add() (page 174) for an example.
If a document, specify a replica set member configuration document as found in the members
array. You must specify _id and the host fields in the member configuration document. See
Pass a Member Configuration Document to rs.add() (page 174) for an example.
See http://docs.mongodb.org/manual/reference/replica-configuration
document for full documentation of all replica set configuration options
param boolean arbiterOnly Applies only if the <host> value is a string. If true, the added host
is an arbiter.
rs.add()
(page
173)
provides
a
wrapper
around
some
of
the
functionality
of
the
replSetReconfig
(page
300)
database
command
and
the
corresponding mongo (page 610) shell helper rs.reconfig() (page 176).
See the
http://docs.mongodb.org/manual/reference/replica-configuration document for
full documentation of all replica set configuration options.
2.1. mongo Shell Methods
173
MongoDB Reference Manual, Release 2.8.0-rc3
Behavior rs.add() (page 173) can, in some cases, force an election for primary which will disconnect the shell.
In such cases, the mongo (page 610) shell displays an error even if the operation succeeds.
Example
Pass a Hostname String to rs.add() The following operation adds a mongod (page 583) instance, running on
the host mongodb3.example.net and accessible on the default port 27017:
rs.add('mongodb3.example.net:27017')
If mongodb3.example.net is an arbiter, use the following form:
rs.add('mongodb3.example.net:27017', true)
Pass a Member Configuration Document to rs.add() Changed in version 2.8.0: Previous version required
an _id file in the document you passed to rs.add() (page 173). After 2.8.0 you can omit the _id field in this
document.
The following operation adds a mongod (page 583) instance, running on the host mongodb4.example.net and
accessible on the default port 27017, as a priority 0 secondary member:
rs.add( { host: "mongodbd4.example.net:27017", priority: 0 } )
You must specify the host field in the member configuration document.
See the http://docs.mongodb.org/manual/reference/replica-configuration for the available
replica set member configuration settings.
See http://docs.mongodb.org/manual/administration/replica-sets for more examples and information.
rs.addArb()
Description
rs.addArb(host)
Adds a new arbiter to an existing replica set.
The rs.addArb() (page 174) method takes the following parameter:
param string host Specifies the hostname and optionally the port number of the arbiter member to
add to replica set.
This function briefly disconnects the shell and forces a reconnection as the replica set renegotiates which member
will be primary. As a result, the shell displays an error even if this command succeeds.
rs.conf()
rs.conf()
Returns a document that contains the current replica set configuration document.
Wraps replSetGetConfig (page 292). See http://docs.mongodb.org/manual/reference/replica-config
for more information on the replica set configuration document.
rs.config()
rs.config() (page 174) is an alias of rs.conf() (page 174).
174
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
rs.freeze()
Description
rs.freeze(seconds)
Makes the current replica set member ineligible to become primary for the period specified.
The rs.freeze() (page 175) method has the following parameter:
param number seconds The duration the member is ineligible to become primary.
rs.freeze() (page 175) provides a wrapper around the database command replSetFreeze (page 291).
rs.help()
rs.help()
Returns a basic help text for all of the replication related shell functions.
rs.initiate()
Description
rs.initiate(configuration)
Initiates a replica set. Optionally takes a configuration argument in the form of a document that holds the
configuration of a replica set.
The rs.initiate() (page 175) method has the following parameter:
param document configuration A document that specifies configuration settings for
the new replica set. If a configuration is not specified, MongoDB uses a default configuration.
The rs.initiate() (page 175) method provides a wrapper around the “replSetInitiate (page 299)”
database command.
Replica Set Configuration See http://docs.mongodb.org/manual/administration/replica-set-member-con
and http://docs.mongodb.org/manual/reference/replica-configuration for examples of
replica set configuration and invitation objects.
rs.printReplicationInfo()
rs.printReplicationInfo()
New in version 2.6.
Prints a formatted report of the status of a replica set from the perspective of the primary member of the set
if run on the primary. 10 The displayed report formats the data returned by db.getReplicationInfo()
(page 117).
Note:
The rs.printReplicationInfo() (page 175) in the mongo (page 610) shell does
not return JSON. Use rs.printReplicationInfo() (page 175) for manual inspection, and
db.getReplicationInfo() (page 117) in scripts.
The output of rs.printReplicationInfo()
db.printReplicationInfo() (page 121).
10
If run on a secondary,
the method calls
db.printSlaveReplicationInfo() (page 122) for details.
2.1. mongo Shell Methods
(page
175)
is
identical
db.printSlaveReplicationInfo()
(page
to
122).
that
of
See
175
MongoDB Reference Manual, Release 2.8.0-rc3
Output Example The following example is a sample output from the rs.printReplicationInfo()
(page 175) method run on the primary:
configured oplog size:
log length start to end:
oplog first event time:
oplog last event time:
now:
192MB
65422secs (18.17hrs)
Mon Jun 23 2014 17:47:18 GMT-0400 (EDT)
Tue Jun 24 2014 11:57:40 GMT-0400 (EDT)
Thu Jun 26 2014 14:24:39 GMT-0400 (EDT)
Output Fields rs.printReplicationInfo() (page 175) formats and prints the data returned by
db.getReplicationInfo() (page 117):
configured oplog size Displays the db.getReplicationInfo.logSizeMB (page 117) value.
log length start to end Displays
the
db.getReplicationInfo.timeDiff
db.getReplicationInfo.timeDiffHours (page 117) values.
(page
117)
and
oplog first event time Displays the db.getReplicationInfo.tFirst (page 117).
oplog last event time Displays the db.getReplicationInfo.tLast (page 118).
now Displays the db.getReplicationInfo.now (page 118).
See db.getReplicationInfo() (page 117) for description of the data.
rs.printSlaveReplicationInfo()
Definition
rs.printSlaveReplicationInfo()
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 db.printSlaveReplicationInfo() (page 122).
Output The following is example output from the rs.printSlaveReplicationInfo() (page 176) method
issued on a replica set with two secondary members:
source: m1.example.net:27017
syncedTo: Thu Apr 10 2014
0 secs (0 hrs) behind the
source: m2.example.net:27017
syncedTo: Thu Apr 10 2014
0 secs (0 hrs) behind the
10:27:47 GMT-0400 (EDT)
primary
10:27:47 GMT-0400 (EDT)
primary
A delayed member may show as 0 seconds behind the primary when the inactivity period on the primary is greater
than the slaveDelay value.
rs.reconfig()
Definition
rs.reconfig(configuration, force)
Reconfigures an existing replica set, overwriting the existing replica set configuration. To run the method, you
must connect to the primary of the replica set.
param document configuration A document that specifies the configuration of a replica set.
param document force If set as { force: true }, this forces the replica set to accept the
new configuration even if a majority of the members are not accessible. Use with caution, as
this can lead to rollback situations.
176
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
When used to reconfigure an existing replica set, first retrieve the current configuration with rs.conf()
(page 174), modify the configuration document as needed, and then pass the modified document to
rs.reconfig() (page 176).
rs.reconfig() (page 176) provides a wrapper around the replSetReconfig (page 300) database command.
Behavior The method disconnects the mongo (page 610) shell and forces a reconnection as the replica set renegotiates which member will be primary. As a result, the shell will display an error even if this command succeeds.
The rs.reconfig() (page 176) shell method can force the current primary to step down and triggers an election
in some situations. When the primary steps down, the primary closes all client connections. This is by design. Since
this typically takes 10-20 seconds, attempt to make such changes during scheduled maintenance periods.
Warning: Using rs.reconfig() (page 176) with { force: true } can lead to rollback situations and
other difficult-to-recover-from situations. Exercise caution when using this option.
Examples A replica set named rs0 has the following configuration:
{
"_id" : "rs0",
"version" : 1,
"members" : [
{
"_id" : 0,
"host" : "mongodb0.example.net:27017"
},
{
"_id" : 1,
"host" : "mongodb1.example.net:27017"
},
{
"_id" : 2,
"host" : "mongodb2.example.net:27017"
}
]
}
The following sequence of operations updates the priority of the second member. The operations are issued
through a mongo (page 610) shell connected to the primary.
cfg = rs.conf();
cfg.members[1].priority = 2;
rs.reconfig(cfg);
1. The first statement uses the rs.conf() (page 174) method to retrieve a document containing the current
configuration for the replica set and sets the document to the local variable cfg.
2. The second statement sets a priority value to the second document in the members array. For additional
settings, see replica set configuration settings.
To access the member configuration document in the array, the statement uses the array index and not the replica
set member’s _id field.
3. The last statement calls the rs.reconfig() (page 176) method with the modified cfg to initialize this new
configuration. Upon successful reconfiguration, the replica set configuration will resemble the following:
2.1. mongo Shell Methods
177
MongoDB Reference Manual, Release 2.8.0-rc3
{
"_id" : "rs0",
"version" : 2,
"members" : [
{
"_id" : 0,
"host" : "mongodb0.example.net:27017"
},
{
"_id" : 1,
"host" : "mongodb1.example.net:27017",
"priority" : 2
},
{
"_id" : 2,
"host" : "mongodb2.example.net:27017"
}
]
}
See also:
http://docs.mongodb.org/manual/reference/replica-configuration
http://docs.mongodb.org/manual/administration/replica-sets.
and
rs.remove()
Definition
rs.remove(hostname)
Removes the member described by the hostname parameter from the current replica set. This function will
disconnect the shell briefly and forces a reconnection as the replica set renegotiates which member will be
primary. As a result, the shell will display an error even if this command succeeds.
The rs.remove() (page 178) method has the following parameter:
param string hostname The hostname of a system in the replica set.
Note: Before running the rs.remove() (page 178) operation, you must shut down the replica set member
that you’re removing.
Changed in version 2.2: This procedure is no longer required when using rs.remove() (page 178), but it
remains good practice.
rs.slaveOk()
rs.slaveOk()
Provides a shorthand for the following operation:
db.getMongo().setSlaveOk()
This allows the current connection to allow read operations to run on secondary members. See the
readPref() (page 93) method for more fine-grained control over read preference in the mongo
(page 610) shell.
178
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
rs.status()
rs.status()
Returns A document with status information.
This output reflects the current status of the replica set, using data derived from the heartbeat packets sent by the
other members of the replica set.
This method provides a wrapper around the replSetGetStatus (page 296) command. See the documentation of the command for a complete description of the output (page 296).
rs.stepDown()
Description
rs.stepDown(seconds)
Forces the current replica set member to step down as primary and then attempt to avoid election as primary for
the designated number of seconds. Produces an error if the current member is not the primary.
The rs.stepDown() (page 179) method has the following parameter:
param number seconds The duration of time that the stepped-down member attempts to avoid reelection as primary. If this parameter is not specified, the method uses the default value of 60
seconds.
This function disconnects the shell briefly and forces a reconnection as the replica set renegotiates which member
will be primary. As a result, the shell will display an error even if this command succeeds.
rs.stepDown() (page 179) provides a wrapper around the database command replSetStepDown
(page 301).
rs.syncFrom()
rs.syncFrom()
New in version 2.2.
Provides a wrapper around the replSetSyncFrom (page 302), which allows administrators to configure the
member of a replica set that the current member will pull data from. Specify the name of the member you want
to replicate from in the form of [hostname]:[port].
See replSetSyncFrom (page 302) for more details.
See http://docs.mongodb.org/manual/tutorial/configure-replica-set-secondary-sync-target
for details how to use this command.
2.1. mongo Shell Methods
179
MongoDB Reference Manual, Release 2.8.0-rc3
180
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
2.1.9 Sharding
Sharding Methods
Name
Description
sh._adminCommand
Runs a database command against the admin database, like db.runCommand()
(page 182)
(page 123), but can confirm that it is issued against a mongos (page 601).
sh._checkFullName()Tests a namespace to determine if its well formed.
(page 182)
sh._checkMongos() Tests to see if the mongo (page 610) shell is connected to a mongos (page 601)
(page 182)
instance.
sh._lastMigration()Reports on the last chunk migration.
(page 182)
sh.addShard()
Adds a shard to a sharded cluster.
(page 183)
sh.addShardTag()
Associates a shard with a tag, to support tag aware sharding.
(page 184)
sh.addTagRange()
Associates range of shard keys with a shard tag, to support tag aware
(page 184)
sharding.
sh.disableBalancing()
Disable balancing on a single collection in a sharded database. Does not affect
(page 185)
balancing of other collections in a sharded cluster.
sh.enableBalancing()
Activates the sharded collection balancer process if previously disabled using
(page 185)
sh.disableBalancing() (page 185).
sh.enableSharding()Enables sharding on a specific database.
(page 186)
sh.getBalancerHost()
Returns the name of a mongos (page 601) that’s responsible for the balancer process.
(page 186)
sh.getBalancerState()
Returns a boolean to report if the balancer is currently enabled.
(page 186)
sh.help() (page 187) Returns help text for the sh methods.
sh.isBalancerRunning()
Returns a boolean to report if the balancer process is currently migrating chunks.
(page 187)
sh.moveChunk()
Migrates a chunk in a sharded cluster.
(page 187)
sh.removeShardTag()Removes the association between a shard and a shard tag.
(page 188)
sh.removeTagRange()Removes an association between a range shard keys and a shard tag. Use to manage
(page 188)
tag aware sharding.
sh.setBalancerState()
Enables or disables the balancer which migrates chunks between shards.
(page 189)
sh.shardCollection()
Enables sharding for a collection.
(page 189)
sh.splitAt()
Divides an existing chunk into two chunks using a specific value of the shard key as
(page 190)
the dividing point.
sh.splitFind()
Divides an existing chunk that contains a document matching a query into two
(page 190)
approximately equal chunks.
sh.startBalancer() Enables the balancer and waits for balancing to start.
(page 191)
sh.status()
Reports on the status of a sharded cluster, as db.printShardingStatus()
(page 191)
(page 122).
sh.stopBalancer() Disables the balancer and waits for any in progress balancing rounds to complete.
(page 194)
sh.waitForBalancer()
Internal. Waits for the balancer state to change.
(page 195)
sh.waitForBalancerOff()
Internal. Waits until the balancer stops running.
(page 195)
2.1. mongo Shell Methods
181
sh.waitForDLock() Internal. Waits for a specified distributed sharded cluster lock.
(page 195)
sh.waitForPingChange()
Internal. Waits for a change in ping state from one of the mongos (page 601) in the
(page 196)
sharded cluster.
MongoDB Reference Manual, Release 2.8.0-rc3
sh._adminCommand()
Definition
sh._adminCommand(command, checkMongos)
Runs a database command against the admin database of a mongos (page 601) instance.
param string command A database command to run against the admin database.
param boolean checkMongos Require verification that the shell is connected to a mongos
(page 601) instance.
See also:
db.runCommand() (page 123)
sh._checkFullName()
Definition
sh._checkFullName(namespace)
Verifies that a namespace name is well formed.
If the namespace is well formed,
sh._checkFullName() (page 182) method exits with no message.
the
Throws If the namespace is not well formed, sh._checkFullName() (page 182) throws: “name
needs to be fully qualified <db>.<collection>”
The sh._checkFullName() (page 182) method has the following parameter:
param string namespace The namespace of a collection. The namespace is the combination of the
database name and the collection name. Enclose the namespace in quotation marks.
sh._checkMongos()
sh._checkMongos()
Returns nothing
Throws “not connected to a mongos”
The sh._checkMongos() (page 182) method throws an error message if the mongo (page 610) shell is not
connected to a mongos (page 601) instance. Otherwise it exits (no return document or return code).
sh._lastMigration()
Definition
sh._lastMigration(namespace)
Returns information on the last migration performed on the specified database or collection.
The sh._lastMigration() (page 182) method has the following parameter:
param string namespace The namespace of a database or collection within the current database.
Output The sh._lastMigration() (page 182) method returns a document with details about the last migration
performed on the database or collection. The document contains the following output:
sh._lastMigration._id
The id of the migration task.
182
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
sh._lastMigration.server
The name of the server.
sh._lastMigration.clientAddr
The IP address and port number of the server.
sh._lastMigration.time
The time of the last migration, formatted as ISODate.
sh._lastMigration.what
The specific type of migration.
sh._lastMigration.ns
The complete namespace of the collection affected by the migration.
sh._lastMigration.details
A document containing details about the migrated chunk. The document includes min and max sub-documents
with the bounds of the migrated chunk.
sh.addShard()
Definition
sh.addShard(host)
Adds a database instance or replica set to a sharded cluster. The optimal configuration is to deploy shards across
replica sets. This method must be run on a mongos (page 601) instance.
The sh.addShard() (page 183) method has the following parameter:
param string host The hostname of either a standalone database instance or of a replica set. Include
the port number if the instance is running on a non-standard port. Include the replica set name if
the instance is a replica set, as explained below.
The sh.addShard() (page 183) method has the following prototype form:
sh.addShard("<host>")
The host parameter can be in any of the following forms:
[hostname]
[hostname]:[port]
[replica-set-name]/[hostname]
[replica-set-name]/[hostname]:port
Warning: Do not use localhost for the hostname unless your configuration server is also running on
localhost.
New in version 2.6: mongos (page 601) installed from official .deb and .rpm packages have the
bind_ip configuration set to 127.0.0.1 by default.
The sh.addShard() (page 183) method is a helper for the addShard (page 303) command. The addShard
(page 303) command has additional options which are not available with this helper.
Considerations
Balancing When you add a shard to a sharded cluster, you affect the balance of chunks among the shards of a cluster
for all existing sharded collections. The balancer will begin migrating chunks so that the cluster will achieve balance.
See http://docs.mongodb.org/manual/core/sharding-balancing for more information.
2.1. mongo Shell Methods
183
MongoDB Reference Manual, Release 2.8.0-rc3
Hidden Members
Important: You cannot include a hidden member in the seed list provided to sh.addShard() (page 183).
Example To add a shard on a replica set, specify the name of the replica set and the hostname of at least one member
of the replica set, as a seed. If you specify additional hostnames, all must be members of the same replica set.
The following example adds a replica set named repl0 and specifies one member of the replica set:
sh.addShard("repl0/mongodb3.example.net:27327")
sh.addShardTag()
Definition
sh.addShardTag(shard, tag)
New in version 2.2.
Associates a shard with a tag or identifier. MongoDB uses these identifiers to direct chunks that fall within a
tagged range to specific shards. sh.addTagRange() (page 184) associates chunk ranges with tag ranges.
param string shard The name of the shard to which to give a specific tag.
param string tag The name of the tag to add to the shard.
Only issue sh.addShardTag() (page 184) when connected to a mongos (page 601) instance.
Example The following example adds three tags, NYC, LAX, and NRT, to three shards:
sh.addShardTag("shard0000", "NYC")
sh.addShardTag("shard0001", "LAX")
sh.addShardTag("shard0002", "NRT")
See also:
sh.addTagRange() (page 184) and sh.removeShardTag() (page 188).
sh.addTagRange()
Definition
sh.addTagRange(namespace, minimum, maximum, tag)
New in version 2.2.
Attaches a range of shard key values to a shard tag created using the sh.addShardTag() (page 184) method.
sh.addTagRange() (page 184) takes the following arguments:
param string namespace The namespace of the sharded collection to tag.
param document minimum The minimum value of the shard key range to include in the
tag. The minimum is an inclusive match. Specify the minimum value in the form of
<fieldname>:<value>. This value must be of the same BSON type or types as the shard
key.
param document maximum The maximum value of the shard key range to include in the
tag. The maximum is an exclusive match. Specify the maximum value in the form of
<fieldname>:<value>. This value must be of the same BSON type or types as the shard
key.
184
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
param string tag The name of the tag to attach the range specified by the minimum and maximum
arguments to.
Use sh.addShardTag() (page 184) to ensure that the balancer migrates documents that exist within the
specified range to a specific shard or set of shards.
Only issue sh.addTagRange() (page 184) when connected to a mongos (page 601) instance.
Behavior
Bounds Shard ranges are always inclusive of the lower value and exclusive of the upper boundary.
Dropped Collections If you add a tag range to a collection using sh.addTagRange() (page 184) and then later
drop the collection or its database, MongoDB does not remove the tag association. If you later create a new collection
with the same name, the old tag association will apply to the new collection.
Example Given a shard key of {state:
zip codes in New York State:
1, zip:
1}, the following operation creates a tag range covering
sh.addTagRange( "exampledb.collection",
{ state: "NY", zip: MinKey },
{ state: "NY", zip: MaxKey },
"NY"
)
sh.disableBalancing()
Description
sh.disableBalancing(namespace)
Disables the balancer for the specified sharded collection. This does not affect the balancing of chunks for other
sharded collections in the same cluster.
The sh.disableBalancing() (page 185) method has the following parameter:
param string namespace The namespace of the collection.
For more information on the balancing process, see http://docs.mongodb.org/manual/tutorial/manage-sharde
and sharding-balancing.
sh.enableBalancing()
Description
sh.enableBalancing(namespace)
Enables the balancer for the specified namespace of the sharded collection.
The sh.enableBalancing() (page 185) method has the following parameter:
param string namespace The namespace of the collection.
Important: sh.enableBalancing() (page 185) does not start balancing. Rather, it allows balancing of
this collection the next time the balancer runs.
For more information on the balancing process, see http://docs.mongodb.org/manual/tutorial/manage-sharde
and sharding-balancing.
2.1. mongo Shell Methods
185
MongoDB Reference Manual, Release 2.8.0-rc3
sh.enableSharding()
Definition
sh.enableSharding(database)
Enables sharding on the specified database. This does not automatically shard any collections but makes it
possible to begin sharding collections using sh.shardCollection() (page 189).
The sh.enableSharding() (page 186) method has the following parameter:
param string database The name of the database shard. Enclose the name in quotation marks.
See also:
sh.shardCollection() (page 189)
sh.getBalancerHost()
sh.getBalancerHost()
Returns String in form hostname:port
sh.getBalancerHost() (page 186) returns the name of the server that is running the balancer.
See also:
• sh.enableBalancing() (page 185)
• sh.disableBalancing() (page 185)
• sh.getBalancerState() (page 186)
• sh.isBalancerRunning() (page 187)
• sh.setBalancerState() (page 189)
• sh.startBalancer() (page 191)
• sh.stopBalancer() (page 194)
• sh.waitForBalancer() (page 195)
• sh.waitForBalancerOff() (page 195)
sh.getBalancerState()
sh.getBalancerState()
Returns boolean
sh.getBalancerState() (page 186) returns true when the balancer is enabled and false if the balancer
is disabled. This does not reflect the current state of balancing operations: use sh.isBalancerRunning()
(page 187) to check the balancer’s current state.
See also:
• sh.enableBalancing() (page 185)
• sh.disableBalancing() (page 185)
• sh.getBalancerHost() (page 186)
• sh.isBalancerRunning() (page 187)
• sh.setBalancerState() (page 189)
186
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
• sh.startBalancer() (page 191)
• sh.stopBalancer() (page 194)
• sh.waitForBalancer() (page 195)
• sh.waitForBalancerOff() (page 195)
sh.help()
sh.help()
Returns a basic help text for all sharding related shell functions.
sh.isBalancerRunning()
sh.isBalancerRunning()
Returns boolean
Returns true if the balancer process is currently running and migrating chunks and false if the balancer process is
not running. Use sh.getBalancerState() (page 186) to determine if the balancer is enabled or disabled.
See also:
• sh.enableBalancing() (page 185)
• sh.disableBalancing() (page 185)
• sh.getBalancerHost() (page 186)
• sh.getBalancerState() (page 186)
• sh.setBalancerState() (page 189)
• sh.startBalancer() (page 191)
• sh.stopBalancer() (page 194)
• sh.waitForBalancer() (page 195)
• sh.waitForBalancerOff() (page 195)
sh.moveChunk()
Definition
sh.moveChunk(namespace, query, destination)
Moves the chunk that contains the document specified by the query to the destination shard.
sh.moveChunk() (page 187) provides a wrapper around the moveChunk (page 310) database command
and takes the following arguments:
param string namespace The namespace of the sharded collection that contains the chunk to migrate.
param document query An equality match on the shard key that selects the chunk to move.
param string destination The name of the shard to move.
Important: In most circumstances, allow the balancer to automatically migrate chunks, and avoid calling
sh.moveChunk() (page 187) directly.
2.1. mongo Shell Methods
187
MongoDB Reference Manual, Release 2.8.0-rc3
See also:
moveChunk
(page
310),
sh.splitAt()
(page
190),
sh.splitFind()
http://docs.mongodb.org/manual/sharding, and chunk migration.
(page
190),
Example Given the people collection in the records database, the following operation finds the chunk that
contains the documents with the zipcode field set to 53187 and then moves that chunk to the shard named
shard0019:
sh.moveChunk("records.people", { zipcode: "53187" }, "shard0019")
sh.removeShardTag()
Definition
sh.removeShardTag(shard, tag)
New in version 2.2.
Removes the association between a tag and a shard. Only issue sh.removeShardTag() (page 188) when
connected to a mongos (page 601) instance.
param string shard The name of the shard from which to remove a tag.
param string tag The name of the tag to remove from the shard.
See also:
sh.addShardTag() (page 184), sh.addTagRange() (page 184)
sh.removeTagRange()
Definition
sh.removeTagRange(namespace, minimum, maximum, tag)
New in version 2.8.
Removes a range of shard key values to a shard tag created using the sh.removeShardTag() (page 188)
method. sh.removeTagRange() (page 188) takes the following arguments:
param string namespace The namespace of the sharded collection to tag.
param document minimum The minimum value of the shard key from the tag. Specify the minimum value in the form of <fieldname>:<value>. This value must be of the same BSON
type or types as the shard key.
param document maximum The maximum value of the shard key range from the tag. Specify the
maximum value in the form of <fieldname>:<value>. This value must be of the same
BSON type or types as the shard key.
param string tag The name of the tag attached to the range specified by the minimum and
maximum arguments to.
Use sh.removeShardTag() (page 188) to ensure that unused or out of date ranges are removed and hence
chunks are balanced as required.
Only issue sh.removeTagRange() (page 188) when connected to a mongos (page 601) instance.
188
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Example Given a shard key of {state:
covering zip codes in New York State:
1, zip:
1}, the following operation removes an existing tag range
sh.removeTagRange( "exampledb.collection",
{ state: "NY", zip: MinKey },
{ state: "NY", zip: MaxKey },
"NY"
)
sh.setBalancerState()
Description
sh.setBalancerState(state)
Enables or disables the balancer. Use sh.getBalancerState() (page 186) to determine if the balancer is
currently enabled or disabled and sh.isBalancerRunning() (page 187) to check its current state.
The sh.getBalancerState() (page 186) method has the following parameter:
param Boolean state Set this to true to enable the balancer and false to disable it.
See also:
• sh.enableBalancing() (page 185)
• sh.disableBalancing() (page 185)
• sh.getBalancerHost() (page 186)
• sh.getBalancerState() (page 186)
• sh.isBalancerRunning() (page 187)
• sh.startBalancer() (page 191)
• sh.stopBalancer() (page 194)
• sh.waitForBalancer() (page 195)
• sh.waitForBalancerOff() (page 195)
sh.shardCollection()
Definition
sh.shardCollection(namespace, key, unique)
Shards a collection using the key as a the shard key. sh.shardCollection() (page 189) takes the following arguments:
param string namespace The namespace of the collection to shard.
param document key A document that specifies the shard key to use to partition and distribute
objects among the shards. A shard key may be one field or multiple fields. A shard key with
multiple fields is called a “compound shard key.”
param Boolean unique When true, ensures that the underlying index enforces a unique constraint.
Hashed shard keys do not support unique constraints.
New in version 2.4: Use the form {field:
may not be compound indexes.
2.1. mongo Shell Methods
"hashed"} to create a hashed shard key. Hashed shard keys
189
MongoDB Reference Manual, Release 2.8.0-rc3
Considerations MongoDB provides no method to deactivate sharding for a collection after calling
shardCollection (page 314). Additionally, after shardCollection (page 314), you cannot change shard
keys or modify the value of any field used in your shard key index.
Example Given the people collection in the records database, the following command shards the collection by
the zipcode field:
sh.shardCollection("records.people", { zipcode: 1} )
Additional
Information shardCollection
(page
314)
for
additional
options,
http://docs.mongodb.org/manual/sharding and http://docs.mongodb.org/manual/core/sharding-intr
for an overview of sharding, http://docs.mongodb.org/manual/tutorial/deploy-shard-cluster
for a tutorial, and sharding-shard-key for choosing a shard key.
sh.splitAt()
Definition
sh.splitAt(namespace, query)
Splits the chunk containing the document specified by the query as if that document were at the “middle” of the
collection, even if the specified document is not the actual median of the collection.
param string namespace The namespace (i.e. <database>.<collection>) of the sharded
collection that contains the chunk to split.
param document query A query to identify a document in a specific chunk. Typically specify the
shard key for a document as the query.
Use this command to manually split chunks unevenly. Use the “sh.splitFind() (page 190)” function to
split a chunk at the actual median.
In most circumstances, you should leave chunk splitting to the automated processes within MongoDB. However,
when initially deploying a sharded cluster it is necessary to perform some measure of pre-splitting using manual
methods including sh.splitAt() (page 190).
sh.splitFind()
Definition
sh.splitFind(namespace, query)
Splits the chunk containing the document specified by the query at its median point, creating two roughly
equal chunks. Use sh.splitAt() (page 190) to split a collection in a specific point.
In most circumstances, you should leave chunk splitting to the automated processes. However, when initially
deploying a sharded cluster it is necessary to perform some measure of pre-splitting using manual methods
including sh.splitFind() (page 190).
param string namespace The namespace (i.e. <database>.<collection>) of the sharded
collection that contains the chunk to split.
param document query A query to identify a document in a specific chunk. Typically specify the
shard key for a document as the query.
190
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
sh.startBalancer()
Definition
sh.startBalancer(timeout, interval)
Enables the balancer in a sharded cluster and waits for balancing to initiate.
param integer timeout Milliseconds to wait.
param integer interval Milliseconds to sleep each cycle of waiting.
See also:
• sh.enableBalancing() (page 185)
• sh.disableBalancing() (page 185)
• sh.getBalancerHost() (page 186)
• sh.getBalancerState() (page 186)
• sh.isBalancerRunning() (page 187)
• sh.setBalancerState() (page 189)
• sh.stopBalancer() (page 194)
• sh.waitForBalancer() (page 195)
• sh.waitForBalancerOff() (page 195)
sh.status()
Definition
sh.status()
Prints a formatted report of the sharding configuration and the information regarding existing chunks in a
sharded cluster. The default behavior suppresses the detailed chunk information if the total number of chunks
is greater than or equal to 20.
The sh.status() (page 191) method has the following parameter:
param Boolean verbose If true, the method displays details of the document distribution across
chunks when you have 20 or more chunks.
See also:
db.printShardingStatus() (page 122)
Output Examples The Sharding Version (page 193) section displays information on the config database:
--- Sharding Status --sharding version: {
"_id" : <num>,
"minCompatibleVersion" : <num>,
"currentVersion" : <num>,
"clusterId" : <ObjectId>
}
The Shards (page 193) section lists information on the shard(s). For each shard, the section displays the name, host,
and the associated tags, if any.
2.1. mongo Shell Methods
191
MongoDB Reference Manual, Release 2.8.0-rc3
shards:
{ "_id" : <shard name1>,
"host" : <string>,
"tags" : [ <string> ... ]
}
{ "_id" : <shard name2>,
"host" : <string>,
"tags" : [ <string> ... ]
}
...
New in version 2.8.0: The Balancer (page 193) section lists information about the state of the balancer. This provides
insight into current balancer operation and can be useful when troubleshooting an unbalanced sharded cluster.
balancer:
Currently enabled: yes
Currently running: yes
Balancer lock taken at Wed Dec 10 2014 12:00:16 GMT+1100 (AEDT) by
Pixl.local:27017:1418172757:16807:Balancer:282475249
Collections with active migrations:
test.t2 started at Wed Dec 10 2014 11:54:51 GMT+1100 (AEDT)
Failed balancer rounds in last 5 attempts: 1
Last reported error: tag ranges not valid for: test.t2
Time of Reported error: Wed Dec 10 2014 12:00:33 GMT+1100 (AEDT)
Migration Results for the last 24 hours:
96 : Success
15 : Failed with error 'ns not found, should be impossible', from
shard01 to shard02
The Databases (page 194) section lists information on the database(s). For each database, the section displays the
name, whether the database has sharding enabled, and the primary shard for the database.
databases:
{ "_id" : <dbname1>,
"partitioned" : <boolean>,
"primary" : <string>
}
{ "_id" : <dbname2>,
"partitioned" : <boolean>,
"primary" : <string>
}
...
The Sharded Collection (page 194) section provides information on the sharding details for sharded collection(s). For
each sharded collection, the section displays the shard key, the number of chunks per shard(s), the distribution of
documents across chunks 11 , and the tag information, if any, for shard key range(s).
<dbname>.<collection>
shard key: { <shard key> : <1 or hashed> }
chunks:
<shard name1> <number of chunks>
<shard name2> <number of chunks>
...
{ <shard key>: <min range1> } -->> { <shard key> : <max range1> } on : <shard name> <last modified
{ <shard key>: <min range2> } -->> { <shard key> : <max range2> } on : <shard name> <last modified
...
11 The sharded collection section, by default, displays the chunk information if the total number of chunks is less than 20. To display the
information when you have 20 or more chunks, call the sh.status() (page 191) methods with the verbose parameter set to true, i.e.
sh.status(true).
192
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
tag: <tag1>
...
{ <shard key> : <min range1> } -->> { <shard key> : <max range1> }
Output Fields
Sharding Version
sh.status.sharding-version._id
The _id (page 193) is an identifier for the version details.
sh.status.sharding-version.minCompatibleVersion
The minCompatibleVersion (page 193) is the minimum compatible version of the config server.
sh.status.sharding-version.currentVersion
The currentVersion (page 193) is the current version of the config server.
sh.status.sharding-version.clusterId
The clusterId (page 193) is the identification for the sharded cluster.
Shards
sh.status.shards._id
The _id (page 193) displays the name of the shard.
sh.status.shards.host
The host (page 193) displays the host location of the shard.
sh.status.shards.tags
The tags (page 193) displays all the tags for the shard. The field only displays if the shard has tags.
Balancer New in version 2.8.0: sh.status() (page 191) added the balancer field.
sh.status.balancer.currently-enabled
currently-enabled (page 193) indicates if the balancer is currently enabled on the sharded cluster.
sh.status.balancer.currently-running
currently-running (page 193) indicates whether the balancer is currently running, and therefore currently
balancing the cluster.
If the balancer is running, currently-running (page 193) lists the process that holds the balancer lock,
and the date and time that the process obtained the lock.
sh.status.balancer.collections-with-active-migrations
collections-with-active-migrations (page 193) lists the names of any collections with active
migrations, and specifies when the migration began. If there are no active migrations, this field will not appear
in the sh.status() (page 191) output.
sh.status.balancer.failed-balancer-rounds-in-last-5-attempts
failed-balancer-rounds-in-last-5-attempts (page 193) displays the number of balancer
rounds that failed, from among the last five attempted rounds. A balancer round will fail when a chunk migration fails.
sh.status.balancer.last-reported-error
last-reported-error (page 193) lists the most recent balancer error message. If there have been no
errors, this field will not appear in the sh.status() (page 191) output.
sh.status.balancer.time-of-reported-error
time-of-reported-error (page 193) provides the date and time of the most recently-reported error.
2.1. mongo Shell Methods
193
MongoDB Reference Manual, Release 2.8.0-rc3
sh.status.balancer.migration-results-for-the-last-24-hours
migration-results-for-the-last-24-hours (page 193) displays the number of migrations in
the last 24 hours, and the error messages from failed migrations . If there have been no recent migrations,
migration-results-for-the-last-24-hours (page 193) displays No recent migrations.
migration-results-for-the-last-24-hours (page 193) includes all migrations, including those
not initiated by the balancer.
Databases
sh.status.databases._id
The _id (page 194) displays the name of the database.
sh.status.databases.partitioned
The partitioned (page 194) displays whether the database has sharding enabled. If true, the database has
sharding enabled.
sh.status.databases.primary
The primary (page 194) displays the primary shard for the database.
Sharded Collection
sh.status.databases.shard-key
The shard-key (page 194) displays the shard key specification document.
sh.status.databases.chunks
The chunks (page 194) lists all the shards and the number of chunks that reside on each shard.
sh.status.databases.chunk-details
The chunk-details (page 194) lists the details of the chunks 1 :
•The range of shard key values that define the chunk,
•The shard where the chunk resides, and
•The last modified timestamp for the chunk.
sh.status.databases.tag
The tag (page 194) lists the details of the tags associated with a range of shard key values.
sh.stopBalancer()
Definition
sh.stopBalancer(timeout, interval)
Disables the balancer in a sharded cluster and waits for balancing to complete.
param integer timeout Milliseconds to wait.
param integer interval Milliseconds to sleep each cycle of waiting.
See also:
• sh.enableBalancing() (page 185)
• sh.disableBalancing() (page 185)
• sh.getBalancerHost() (page 186)
• sh.getBalancerState() (page 186)
• sh.isBalancerRunning() (page 187)
• sh.setBalancerState() (page 189)
• sh.startBalancer() (page 191)
194
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
• sh.waitForBalancer() (page 195)
• sh.waitForBalancerOff() (page 195)
sh.waitForBalancer()
Definition
sh.waitForBalancer(wait, timeout, interval)
Waits for a change in the state of the balancer. sh.waitForBalancer() (page 195) is an internal method,
which takes the following arguments:
param Boolean wait Set to true to ensure the balancer is now active. The default is false, which
waits until balancing stops and becomes inactive.
param integer timeout Milliseconds to wait.
param integer interval Milliseconds to sleep.
sh.waitForBalancerOff()
Definition
sh.waitForBalancerOff(timeout, interval)
Internal method that waits until the balancer is not running.
param integer timeout Milliseconds to wait.
param integer interval Milliseconds to sleep.
See also:
• sh.enableBalancing() (page 185)
• sh.disableBalancing() (page 185)
• sh.getBalancerHost() (page 186)
• sh.getBalancerState() (page 186)
• sh.isBalancerRunning() (page 187)
• sh.setBalancerState() (page 189)
• sh.startBalancer() (page 191)
• sh.stopBalancer() (page 194)
• sh.waitForBalancer() (page 195)
sh.waitForDLock()
Definition
sh.waitForDLock(lockname, wait, timeout, interval)
Waits until the specified distributed lock changes state. sh.waitForDLock() (page 195) is an internal
method that takes the following arguments:
param string lockname The name of the distributed lock.
param Boolean wait Set to true to ensure the balancer is now active. Set to false to wait until
balancing stops and becomes inactive.
param integer timeout Milliseconds to wait.
2.1. mongo Shell Methods
195
MongoDB Reference Manual, Release 2.8.0-rc3
param integer interval Milliseconds to sleep in each waiting cycle.
sh.waitForPingChange()
Definition
sh.waitForPingChange(activePings, timeout, interval)
sh.waitForPingChange() (page 196) waits for a change in ping state of one of the activepings, and
only returns when the specified ping changes state.
param array activePings An array of active pings from the mongos (page 685) collection.
param integer timeout Number of milliseconds to wait for a change in ping state.
param integer interval Number of milliseconds to sleep in each waiting cycle.
2.1.10 Subprocess
Subprocess Methods
Name
clearRawMongoProgramOutput() (page 196)
rawMongoProgramOutput() (page 196)
run()
runMongoProgram() (page 197)
runProgram() (page 197)
startMongoProgram()
stopMongoProgram() (page 197)
stopMongoProgramByPid() (page 197)
stopMongod() (page 197)
waitMongoProgramOnPort() (page 197)
waitProgram() (page 197)
Description
For internal use.
For internal use.
For internal use.
For internal use.
For internal use.
For internal use.
For internal use.
For internal use.
For internal use.
For internal use.
For internal use.
clearRawMongoProgramOutput()
clearRawMongoProgramOutput()
For internal use.
rawMongoProgramOutput()
rawMongoProgramOutput()
For internal use.
run()
run()
For internal use.
196
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
runMongoProgram()
runMongoProgram()
For internal use.
runProgram()
runProgram()
For internal use.
startMongoProgram()
_startMongoProgram()
For internal use.
stopMongoProgram()
stopMongoProgram()
For internal use.
stopMongoProgramByPid()
stopMongoProgramByPid()
For internal use.
stopMongod()
stopMongod()
For internal use.
waitMongoProgramOnPort()
waitMongoProgramOnPort()
For internal use.
waitProgram()
waitProgram()
For internal use.
2.1. mongo Shell Methods
197
MongoDB Reference Manual, Release 2.8.0-rc3
2.1.11 Constructors
Object Constructors and Methods
Name
BulkWriteResult() (page 198)
Date() (page 199)
Description
Wrapper around the result set from Bulk.execute() (page 137).
Creates a date object. By default creates a date object including the
current date.
Returns the timestamp portion of an ObjectId.
ObjectId.getTimestamp()
(page 199)
ObjectId.toString()
Displays the string representation of an ObjectId.
(page 200)
ObjectId.valueOf()
Displays the str attribute of an ObjectId as a hexadecimal string.
(page 200)
UUID() (page 200)
Converts a 32-byte hexadecimal string to the UUID BSON subtype.
WriteResult() (page 201)
Wrapper around the result set from write methods.
WriteResult.hasWriteConcernError()
Returns a boolean specifying whether whether the results include
(page 202)
WriteResult.writeConcernError (page 201).
WriteResult.hasWriteError() Returns a boolean specifying whether the results include
(page 202)
WriteResult.writeError (page 201).
BulkWriteResult()
BulkWriteResult()
New in version 2.6.
A wrapper that contains the results of the Bulk.execute() (page 137) method.
Properties The BulkWriteResult (page 198) has the following properties:
BulkWriteResult.nInserted
The number of documents inserted using the Bulk.insert() (page 148) method. For documents inserted
through operations with the Bulk.find.upsert() (page 144) option, see the nUpserted (page 198) field
instead.
BulkWriteResult.nMatched
The number of existing documents selected for update or replacement. If the update/replacement operation
results in no change to an existing document, e.g. $set (page 459) expression updates the value to the current
value, nMatched (page 198) can be greater than nModified (page 198).
BulkWriteResult.nModified
The number of existing documents updated or replaced. If the update/replacement operation results in no change
to an existing document, such as setting the value of the field to its current value, nModified (page 198) can
be less than nMatched (page 198). Inserted documents do not affect the number of nModified (page 198);
refer to the nInserted (page 198) and nUpserted (page 198) fields instead.
BulkWriteResult.nRemoved
The number of documents removed.
BulkWriteResult.nUpserted
The number of documents inserted through operations with the Bulk.find.upsert() (page 144) option.
BulkWriteResult.upserted
An array of documents that contains information for each document inserted through operations with the
Bulk.find.upsert() (page 144) option.
198
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Each document contains the following information:
BulkWriteResult.upserted.index
An integer that identifies the operation in the bulk operations list, which uses a zero-based index.
BulkWriteResult.upserted._id
The _id value of the inserted document.
BulkWriteResult.writeErrors
An array of documents that contains information regarding any error, unrelated to write concerns, encountered
during the update operation. The writeErrors (page 199) array contains an error document for each write
operation that errors.
Each error document contains the following fields:
BulkWriteResult.writeErrors.index
An integer that identifies the write operation in the bulk operations list, which uses a zero-based index. See
also Bulk.getOperations() (page 147).
BulkWriteResult.writeErrors.code
An integer value identifying the error.
BulkWriteResult.writeErrors.errmsg
A description of the error.
BulkWriteResult.writeErrors.op
A document identifying the operation that failed. For instance, an update/replace operation error will return
a document specifying the query, the update, the multi and the upsert options; an insert operation will
return the document the operation tried to insert.
BulkWriteResult.writeConcernError
Document that describe error related to write concern and contains the field:
BulkWriteResult.writeConcernError.code
An integer value identifying the cause of the write concern error.
BulkWriteResult.writeConcernError.errInfo
A document identifying the write concern setting related to the error.
BulkWriteResult.writeConcernError.errmsg
A description of the cause of the write concern error.
Date()
Date()
Returns Current date, as a string.
ObjectId.getTimestamp()
ObjectId.getTimestamp()
Returns The timestamp portion of the ObjectId() object as a Date.
In the following example, call the getTimestamp() (page 199) method on an ObjectId (e.g.
ObjectId("507c7f79bcf86cd7994f6c0e")):
ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp()
This will return the following output:
2.1. mongo Shell Methods
199
MongoDB Reference Manual, Release 2.8.0-rc3
ISODate("2012-10-15T21:26:17Z")
ObjectId.toString()
ObjectId.toString()
Returns The string representation of the ObjectId() object.
ObjectId(...).
This value has the format of
Changed in version 2.2: In previous versions ObjectId.toString() (page 200) returns the value of the
ObjectId as a hexadecimal string.
In the following example, call the toString() (page 200) method on an ObjectId (e.g.
ObjectId("507c7f79bcf86cd7994f6c0e")):
ObjectId("507c7f79bcf86cd7994f6c0e").toString()
This will return the following string:
ObjectId("507c7f79bcf86cd7994f6c0e")
You can confirm the type of this object using the following operation:
typeof ObjectId("507c7f79bcf86cd7994f6c0e").toString()
ObjectId.valueOf()
ObjectId.valueOf()
Returns The value of the ObjectId() object as a lowercase hexadecimal string. This value is the str
attribute of the ObjectId() object.
Changed in version 2.2: In previous versions ObjectId.valueOf() (page 200) returns the ObjectId()
object.
In the following example, call the valueOf() (page 200) method on an ObjectId (e.g.
ObjectId("507c7f79bcf86cd7994f6c0e")):
ObjectId("507c7f79bcf86cd7994f6c0e").valueOf()
This will return the following string:
507c7f79bcf86cd7994f6c0e
You can confirm the type of this object using the following operation:
typeof ObjectId("507c7f79bcf86cd7994f6c0e").valueOf()
UUID()
Definition
UUID(<string>)
Generates a BSON UUID object.
param string hex Specify a 32-byte hexadecimal string to convert to the UUID BSON subtype.
Returns A BSON UUID object.
200
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Example Create a 32 byte hexadecimal string:
var myuuid = '0123456789abcdeffedcba9876543210'
Convert it to the BSON UUID subtype:
UUID(myuuid)
BinData(3,"ASNFZ4mrze/+3LqYdlQyEA==")
WriteResult()
Definition
WriteResult()
A wrapper that contains the result status of the mongo (page 610) shell write methods.
See
db.collection.insert()
(page
55),
db.collection.update()
db.collection.remove() (page 66), and db.collection.save() (page 70).
(page
72),
Properties The WriteResult (page 201) has the following properties:
WriteResult.nInserted
The number of documents inserted, excluding upserted documents. See WriteResult.nUpserted
(page 201) for the number of documents inserted through an upsert.
WriteResult.nMatched
The number of documents selected for update. If the update operation results in no change to the document, e.g.
$set (page 459) expression updates the value to the current value, nMatched (page 201) can be greater than
nModified (page 201).
WriteResult.nModified
The number of existing documents updated. If the update/replacement operation results in no change to the
document, such as setting the value of the field to its current value, nModified (page 201) can be less than
nMatched (page 201).
WriteResult.nUpserted
The number of documents inserted by an upsert (page 74).
WriteResult._id
The _id of the document inserted by an upsert. Returned only if an upsert results in an insert.
WriteResult.nRemoved
The number of documents removed.
WriteResult.writeError
A document that contains information regarding any error, excluding write concern errors, encountered during
the write operation.
WriteResult.writeError.code
An integer value identifying the error.
WriteResult.writeError.errmsg
A description of the error.
WriteResult.writeConcernError
A document that contains information regarding any write concern errors encountered during the write operation.
2.1. mongo Shell Methods
201
MongoDB Reference Manual, Release 2.8.0-rc3
WriteResult.writeConcernError.code
An integer value identifying the write concern error.
WriteResult.writeConcernError.errInfo
A document identifying the write concern setting related to the error.
WriteResult.writeError.errmsg
A description of the error.
See also:
WriteResult.hasWriteError() (page 202), WriteResult.hasWriteConcernError() (page 202)
WriteResult.hasWriteConcernError()
Definition
WriteResult.hasWriteConcernError()
Returns true if the result of a mongo (page 610) shell write method
WriteResult.writeConcernError (page 201). Otherwise, the method returns false.
See also:
has
WriteResult() (page 201)
WriteResult.hasWriteError()
Definition
WriteResult.hasWriteError()
Returns true if the result of a mongo (page 610) shell write method has WriteResult.writeError
(page 201). Otherwise, the method returns false.
See also:
WriteResult() (page 201)
2.1.12 Connection
Connection Methods
Name
Mongo() (page 202)
Mongo.getDB() (page 203)
Mongo.getReadPrefMode()
(page 203)
Mongo.getReadPrefTagSet()
(page 204)
Mongo.setReadPref() (page 204)
Mongo.setSlaveOk() (page 205)
connect()
Description
Creates a new connection object.
Returns a database object.
Returns the current read preference mode for the MongoDB
connection.
Returns the read preference tag set for the MongoDB connection.
Sets the read preference for the MongoDB connection.
Allows operations on the current connection to read from secondary
members.
Connects to a MongoDB instance and to a specified database on that
instance.
Mongo()
Description
202
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Mongo(host)
JavaScript constructor to instantiate a database connection from the mongo (page 610) shell or from a JavaScript
file.
The Mongo() (page 202) method has the following parameter:
param string host The host, either in the form of <host> or <host><:port>.
Instantiation Options
on the default port.
Use the constructor without a parameter to instantiate a connection to the localhost interface
Pass the <host> parameter to the constructor to instantiate a connection to the <host> and the default port.
Pass the <host><:port> parameter to the constructor to instantiate a connection to the <host> and the <port>.
See also:
Mongo.getDB() (page 203) and db.getMongo() (page 116).
Mongo.getDB()
Description
Mongo.getDB(<database>)
Provides access to database objects from the mongo (page 610) shell or from a JavaScript file.
The Mongo.getDB() (page 203) method has the following parameter:
param string database The name of the database to access.
Example The following example instantiates a new connection to the MongoDB instance running on the localhost
interface and returns a reference to "myDatabase":
db = new Mongo().getDB("myDatabase");
See also:
Mongo() (page 202) and connect() (page 205)
Mongo.getReadPrefMode()
Mongo.getReadPrefMode()
Returns The current read preference mode for the Mongo() (page 116) connection object.
See http://docs.mongodb.org/manual/core/read-preference for an introduction to read
preferences in MongoDB. Use getReadPrefMode() (page 203) to return the current read preference mode,
as in the following example:
db.getMongo().getReadPrefMode()
Use the following operation to return and print the current read preference mode:
print(db.getMongo().getReadPrefMode());
This operation will return one of the following read preference modes:
•primary
•primaryPreferred
2.1. mongo Shell Methods
203
MongoDB Reference Manual, Release 2.8.0-rc3
•secondary
•secondaryPreferred
•nearest
See also:
http://docs.mongodb.org/manual/core/read-preference,
setReadPref() (page 204), and getReadPrefTagSet() (page 204).
readPref()
(page
93),
Mongo.getReadPrefTagSet()
Mongo.getReadPrefTagSet()
Returns The current read preference tag set for the Mongo() (page 116) connection object.
See http://docs.mongodb.org/manual/core/read-preference for an introduction to read
preferences and tag sets in MongoDB. Use getReadPrefTagSet() (page 204) to return the current read
preference tag set, as in the following example:
db.getMongo().getReadPrefTagSet()
Use the following operation to return and print the current read preference tag set:
printjson(db.getMongo().getReadPrefTagSet());
See also:
http://docs.mongodb.org/manual/core/read-preference,
setReadPref() (page 204), and getReadPrefTagSet() (page 204).
readPref()
(page
93),
Mongo.setReadPref()
Definition
Mongo.setReadPref(mode, tagSet)
Call the setReadPref() (page 204) method on a Mongo (page 116) connection object to control how the
client will route all queries 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 A tag set used to specify custom read preference modes. For details, see
replica-set-read-preference-tag-sets.
Examples To set a read preference mode in the mongo (page 610) shell, use the following operation:
db.getMongo().setReadPref('primaryPreferred')
To set a read preference that uses a tag set, specify an array of tag sets as the second argument to
Mongo.setReadPref() (page 204), as in the following:
db.getMongo().setReadPref('primaryPreferred', [ { "dc": "east" } ] )
You can specify multiple tag sets, in order of preference, as in the following:
204
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.getMongo().setReadPref('secondaryPreferred',
[ { "dc": "east", "use": "production" },
{ "dc": "east", "use": "reporting" },
{ "dc": "east" },
{}
] )
If the replica set cannot satisfy the first tag set, the client will attempt to use the second read preference. Each tag set
can contain zero or more field/value tag pairs, with an “empty” document acting as a wildcard which matches a replica
set member with any tag set or no tag set.
Note: You must call Mongo.setReadPref() (page 204) on the connection object before retrieving documents
using that connection to use that read preference.
mongo.setSlaveOk()
Mongo.setSlaveOk()
For the current session, this command permits read operations from non-master (i.e. slave or secondary) instances. Practically, use this method in the following form:
db.getMongo().setSlaveOk()
Indicates that “eventually consistent” read operations are acceptable for the current application. This function
provides the same functionality as rs.slaveOk() (page 178).
See the readPref() (page 93) method for more fine-grained control over read preference in the
mongo (page 610) shell.
connect()
connect(<hostname><:port>/<database>)
The connect() method creates a connection to a MongoDB instance. However, use the Mongo() (page 202)
object and its getDB() (page 203) method in most cases.
connect() accepts a string <hostname><:port>/<database> parameter to connect to the MongoDB
instance on the <hostname><:port> and return the reference to the database <database>.
The following example instantiates a new connection to the MongoDB instance running on the localhost interface and returns a reference to myDatabase:
db = connect("localhost:27017/myDatabase")
See also:
Mongo.getDB() (page 203)
2.1. mongo Shell Methods
205
MongoDB Reference Manual, Release 2.8.0-rc3
2.1.13 Native
Native Methods
Name
_isWindows()
(page 206)
_rand() (page 206)
_srand() (page 207)
cat()
cd()
copyDbpath()
(page 207)
fuzzFile() (page 207)
getHostName()
(page 207)
getMemInfo()
(page 207)
hostname()
listFiles() (page 208)
load()
ls()
md5sumFile()
(page 208)
mkdir()
pwd()
quit()
removeFile()
(page 209)
resetDbpath()
(page 209)
version()
Description
Returns true if the shell runs on a Windows system; false if a Unix or Linux
system.
Returns a random number between 0 and 1.
For internal use.
Returns the contents of the specified file.
Changes the current working directory to the specified path.
Copies a local dbPath. For internal use.
For internal use to support testing.
Returns the hostname of the system running the mongo (page 610) shell.
Returns a document that reports the amount of memory used by the shell.
Returns the hostname of the system running the shell.
Returns an array of documents that give the name and size of each object in the
directory.
Loads and runs a JavaScript file in the shell.
Returns a list of the files in the current directory.
The md5 hash of the specified file.
Creates a directory at the specified path.
Returns the current directory.
Exits the current shell session.
Removes the specified file from the local file system.
Removes a local dbPath. For internal use.
Returns the current version of the mongo (page 610) shell instance.
_isWindows()
_isWindows()
Returns boolean.
Returns “true” if the mongo (page 610) shell is running on a system that is Windows, or “false” if the shell is
running on a Unix or Linux systems.
rand()
_rand()
Returns A random number between 0 and 1.
This function provides functionality similar to the Math.rand() function from the standard library.
206
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
_srand()
_srand()
For internal use.
cat()
Definition
cat(filename)
Returns the contents of the specified file. The method returns with output relative to the current shell session
and does not impact the server.
param string filename Specify a path and file name on the local file system.
cd()
Definition
cd(path)
param string path A path on the file system local to the mongo (page 610) shell context.
cd() changes the directory context of the mongo (page 610) shell and has no effect on the MongoDB server.
copyDbpath()
copyDbpath()
For internal use.
fuzzFile()
Description
fuzzFile(filename)
For internal use.
param string filename A filename or path to a local file.
getHostName()
getHostName()
Returns The hostname of the system running the mongo (page 610) shell process.
getMemInfo()
getMemInfo()
Returns a document with two fields that report the amount of memory used by the JavaScript shell process. The
fields returned are resident and virtual.
2.1. mongo Shell Methods
207
MongoDB Reference Manual, Release 2.8.0-rc3
hostname()
hostname()
Returns The hostname of the system running the mongo (page 610) shell process.
listFiles()
listFiles()
Returns an array, containing one document per object in the directory. This function operates in the context of
the mongo (page 610) process. The included fields are:
name
Returns a string which contains the name of the object.
isDirectory
Returns true or false if the object is a directory.
size
Returns the size of the object in bytes. This field is only present for files.
load()
Definition
load(file)
Loads and runs a JavaScript file into the current shell environment.
The load() method has the following parameter:
param string filename Specifies the path of a JavaScript file to execute.
Specify filenames with relative or absolute paths. When using relative path names, confirm the current directory
using the pwd() method.
After executing a file with load(), you may reference any functions or variables defined the file from the
mongo (page 610) shell environment.
Example Consider the following examples of the load() method:
load("scripts/myjstest.js")
load("/data/db/scripts/myjstest.js")
ls()
ls()
Returns a list of the files in the current directory.
This function returns with output relative to the current shell session, and does not impact the server.
md5sumFile()
Description
208
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
md5sumFile(filename)
Returns a md5 hash of the specified file.
The md5sumFile() (page 208) method has the following parameter:
param string filename A file name.
Note: The specified filename must refer to a file located on the system running the mongo (page 610) shell.
mkdir()
Description
mkdir(path)
Creates a directory at the specified path. This method creates the entire path specified if the enclosing directory
or directories do not already exit.
This method is equivalent to mkdir -p with BSD or GNU utilities.
The mkdir() method has the following parameter:
param string path A path on the local filesystem.
pwd()
pwd()
Returns the current directory.
This function returns with output relative to the current shell session, and does not impact the server.
quit()
quit()
Exits the current shell session.
removeFile()
Description
removeFile(filename)
Removes the specified file from the local file system.
The removeFile() (page 209) method has the following parameter:
param string filename A filename or path to a local file.
resetDbpath()
resetDbpath()
For internal use.
2.1. mongo Shell Methods
209
MongoDB Reference Manual, Release 2.8.0-rc3
version()
version()
Returns The version of the mongo (page 610) shell as a string.
Changed in version 2.4: In previous versions of the shell, version() would print the version instead of
returning a string.
2.2 Database Commands
All command documentation outlined below describes a command and its available parameters and provides a document template or prototype for each command. Some command documentation also includes the relevant mongo
(page 610) shell helpers.
2.2.1 User Commands
Aggregation Commands
Aggregation Commands
Name
aggregate
(page 210)
count (page 213)
distinct (page 215)
group (page 216)
mapReduce
(page 220)
Description
Performs aggregation tasks such as group using the aggregation framework.
Counts the number of documents in a collection.
Displays the distinct values found for a specified key in a collection.
Groups documents in a collection by the specified key and performs simple
aggregation.
Performs map-reduce aggregation for large data sets.
aggregate
aggregate
New in version 2.2.
Performs aggregation operation using the aggregation pipeline (page 484). The pipeline allows users to process
data from a collection with a sequence of stage-based manipulations.
Changed in version 2.6.
•The aggregate (page 210) command adds support for returning a cursor, supports the explain option,
and enhances its sort operations with an external sort facility.
•aggregation pipeline (page 484) introduces the $out (page 491) operator to allow aggregate
(page 210) command to store results to a collection.
The command has following syntax:
Changed in version 2.6.
{
aggregate: "<collection>",
pipeline: [ <stage>, <...> ],
explain: <boolean>,
210
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
allowDiskUse: <boolean>,
cursor: <document>
}
The aggregate (page 210) command takes the following fields as arguments:
field string aggregate The name of the collection to as the input for the aggregation pipeline.
field array pipeline An array of aggregation pipeline stages (page 484) that process and transform
the document stream as part of the aggregation pipeline.
field boolean explain Specifies to return the information on the processing of the pipeline.
New in version 2.6.
field boolean allowDiskUse Enables writing to temporary files. When set to true, aggregation
stages can write data to the _tmp subdirectory in the dbPath directory.
New in version 2.6.
field document cursor Specify a document that contains options that control the creation of the
cursor object.
New in version 2.6.
For more information about the aggregation pipeline http://docs.mongodb.org/manual/core/aggregation-pipeline
Aggregation Reference (page 564), and http://docs.mongodb.org/manual/core/aggregation-pipeline-limits.
Example
Aggregate Data with Multi-Stage Pipeline A collection articles contains documents such as the following:
{
_id: ObjectId("52769ea0f3dc6ead47c9a1b2"),
author: "abc123",
title: "zzz",
tags: [ "programming", "database", "mongodb" ]
}
The following example performs an aggregate (page 210) operation on the articles collection to calculate the
count of each distinct element in the tags array that appears in the collection.
db.runCommand(
{ aggregate: "articles",
pipeline: [
{ $project: { tags: 1 } },
{ $unwind: "$tags" },
{ $group: {
_id: "$tags",
count: { $sum : 1 }
}
}
]
}
)
In the mongo (page 610) shell, this operation can use the aggregate() (page 22) helper as in the following:
db.articles.aggregate(
[
{ $project: { tags: 1 } },
2.2. Database Commands
211
MongoDB Reference Manual, Release 2.8.0-rc3
{ $unwind: "$tags" },
{ $group: {
_id: "$tags",
count: { $sum : 1 }
}
}
]
)
Note: In 2.6 and later, the aggregate() (page 22) helper always returns a cursor.
Changed in version 2.4: If an error occurs, the aggregate() (page 22) 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 210) command.
Return Information on the Aggregation Operation The following aggregation operation sets the optional field
explain to true to return information about the aggregation operation.
db.runCommand( { aggregate: "orders",
pipeline: [
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
],
explain: true
} )
Note: The intended readers of the explain output document are humans, and not machines, and the output format
is subject to change between releases.
See also:
db.collection.aggregate() (page 22) method
Aggregate Data using 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:
db.runCommand(
{ aggregate: "stocks",
pipeline: [
{ $project : { cusip: 1, date: 1, price: 1, _id: 0 } },
{ $sort : { cusip : 1, date: 1 } }
],
allowDiskUse: true
}
)
See also:
db.collection.aggregate() (page 22)
Aggregate Command Returns a Cursor
Note: Using the aggregate (page 210) command to return a cursor is a low-level operation, intended for authors
of drivers. Most users should use the db.collection.aggregate() (page 22) helper provided in the mongo
(page 610) shell or in their driver. In 2.6 and later, the aggregate() (page 22) helper always returns a cursor.
212
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
The following command returns a document that contains results with which to instantiate a cursor object.
db.runCommand(
{ aggregate: "records",
pipeline: [
{ $project: { name: 1, email: 1, _id: 0 } },
{ $sort: { name: 1 } }
],
cursor: { }
}
)
To specify an initial batch size, specify the batchSize in the cursor field, as in the following example:
db.runCommand(
{ aggregate: "records",
pipeline: [
{ $project: { name: 1, email: 1, _id: 0 } },
{ $sort: { name: 1 } }
],
cursor: { batchSize: 0 }
}
)
The {batchSize: 0 } document specifies the size of the initial batch size only. Specify subsequent batch sizes
to OP_GET_MORE12 operations as with other MongoDB cursors. A batchSize of 0 means an empty first batch
and is useful if you want to quickly get back a cursor or failure message, without doing significant server-side work.
See also:
db.collection.aggregate() (page 22)
count
Definition
count
Counts the number of documents in a collection. Returns a document that contains this count and as well as the
command status. count (page 213) has the following form:
Changed in version 2.6: count (page 213) now accepts the hint option to specify an index.
{ count: <collection>, query: <query>, limit: <limit>, skip: <skip>, hint: <hint> }
count (page 213) has the following fields:
field string count The name of the collection to count.
field document query A query that selects which documents to count in a collection.
field integer limit The maximum number of matching documents to return.
field integer skip The number of matching documents to skip before returning results.
field String,document hint The index to use. Specify either the index name as a string or the index
specification document.
New in version 2.6.
12 http://docs.mongodb.org/meta-driver/latest/legacy/mongodb-wire-protocol/#wire-op-get-more
2.2. Database Commands
213
MongoDB Reference Manual, Release 2.8.0-rc3
MongoDB also provides the count() (page 83) and db.collection.count() (page 26) wrapper methods in the mongo (page 610) shell.
Behavior On a sharded cluster, count (page 213) 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 486) stage of the
db.collection.aggregate() (page 22) method to $sum (page 554) the documents. For example, the
following operation counts the documents in a collection:
db.collection.aggregate(
[
{ $group: { _id: null, count: { $sum: 1 } } }
]
)
To get a count of documents that match a query condition, include the $match (page 490) stage as well:
db.collection.aggregate(
[
{ $match: <query condition> },
{ $group: { _id: null, count: { $sum: 1 } } }
]
)
See Perform a Count (page 491) for an example.
Examples The following sections provide examples of the count (page 213) command.
Count All Documents The following operation counts the number of all documents in the orders collection:
db.runCommand( { count: 'orders' } )
In the result, the n, which represents the count, is 26, and the command status ok is 1:
{ "n" : 26, "ok" : 1 }
Count Documents That Match a Query The following operation returns a count of the documents in the orders
collection where the value of the ord_dt field is greater than Date(’01/01/2012’):
db.runCommand( { count:'orders',
query: { ord_dt: { $gt: new Date('01/01/2012') } }
} )
In the result, the n, which represents the count, is 13 and the command status ok is 1:
{ "n" : 13, "ok" : 1 }
Skip Documents in Count The following operation returns a count of the documents in the orders collection
where the value of the ord_dt field is greater than Date(’01/01/2012’) and skip the first 10 matching documents:
db.runCommand( { count:'orders',
query: { ord_dt: { $gt: new Date('01/01/2012') } },
skip: 10 } )
214
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
In the result, the n, which represents the count, is 3 and the command status ok is 1:
{ "n" : 3, "ok" : 1 }
Specify the Index to Use The following operation uses the index { status: 1 } to return a count of the
documents in the orders collection where the value of the ord_dt field is greater than Date(’01/01/2012’)
and the status field is equal to "D":
db.runCommand(
{
count:'orders',
query: {
ord_dt: { $gt: new Date('01/01/2012') },
status: "D"
},
hint: { status: 1 }
}
)
In the result, the n, which represents the count, is 1 and the command status ok is 1:
{ "n" : 1, "ok" : 1 }
distinct
Definition
distinct
Finds the distinct values for a specified field across a single collection. distinct (page 215) returns a document that contains an array of the distinct values. The return document also contains a subdocument with query
statistics and the query plan.
When possible, the distinct (page 215) command uses an index to find documents and return values.
The command takes the following form:
{ distinct: "<collection>", key: "<field>", query: <query> }
The command contains the following fields:
field string distinct The name of the collection to query for distinct values.
field string key The field to collect distinct values from.
field document query A query specification to limit the input documents in the distinct analysis.
Examples Return an array of the distinct values of the field ord_dt from all documents in the orders collection:
db.runCommand ( { distinct: "orders", key: "ord_dt" } )
Return an array of the distinct values of the field sku in the subdocument item from all documents in the orders
collection:
db.runCommand ( { distinct: "orders", key: "item.sku" } )
Return an array of the distinct values of the field ord_dt from the documents in the orders collection where the
price is greater than 10:
2.2. Database Commands
215
MongoDB Reference Manual, Release 2.8.0-rc3
db.runCommand ( { distinct: "orders",
key: "ord_dt",
query: { price: { $gt: 10 } }
} )
Note: MongoDB also provides the shell wrapper method db.collection.distinct() (page 28) for the
distinct (page 215) command. Additionally, many MongoDB drivers also provide a wrapper method. Refer to the
specific driver documentation.
group
Definition
group
Groups documents in a collection by the specified key and performs simple aggregation functions, such as
computing counts and sums. The command is analogous to a SELECT <...> GROUP BY statement in SQL.
The command returns a document with the grouped records as well as the command meta-data.
The group (page 216) command takes the following prototype form:
{
group:
{
ns: <namespace>,
key: <key>,
$reduce: <reduce function>,
$keyf: <key function>,
cond: <query>,
finalize: <finalize function>
}
}
The command accepts a document with the following fields:
field string ns The collection from which to perform the group by operation.
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 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 process. If you omit the cond field, group (page 216) processes all the documents in the collection
for the group operation.
field function finalize A function that runs each item in the result set before group (page 216)
returns the final value. This function can either modify the result document or replace the result
document as a whole. Unlike the $keyf and $reduce fields that also specify a function, this
field name is finalize, not $finalize.
216
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
For the shell, MongoDB provides a wrapper method db.collection.group() (page 51). However, the
db.collection.group() (page 51) method takes the keyf field and the reduce field whereas the
group (page 216) command takes the $keyf field and the $reduce field.
Behavior
Limits and Restrictions The group (page 216) command 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 692).
Additionally, 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 220).
Previous versions had a limit of 10,000 elements.
Prior to 2.4, the group (page 216) command took the mongod (page 583) instance’s 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 220), the group (page 216) command, and $where
(page 421) operator expressions cannot access certain global functions or properties, such as db, that are available in
the mongo (page 610) shell.
When upgrading to MongoDB 2.4, you will need to refactor your code if your map-reduce operations
(page 220), group (page 216) commands, or $where (page 421) 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 220), the
group (page 216) command, and $where (page 421) operator expressions in MongoDB 2.4:
Available Properties
Available Functions
args
MaxKey
MinKey
assert()
BinData()
DBPointer()
DBRef()
doassert()
emit()
gc()
HexData()
hex_md5()
isNumber()
isObject()
ISODate()
isString()
Map()
MD5()
NumberInt()
NumberLong()
ObjectId()
print()
printjson()
printjsononeline()
sleep()
Timestamp()
tojson()
tojsononeline()
tojsonObject()
UUID()
version()
JavaScript in MongoDB
Although group (page 216) uses JavaScript, most interactions with MongoDB do not use JavaScript but use an
idiomatic driver in the language of the interacting application.
2.2. Database Commands
217
MongoDB Reference Manual, Release 2.8.0-rc3
Examples The following are examples of the db.collection.group() (page 51) method. The examples
assume an orders collection with documents of the following prototype:
{
_id: ObjectId("5085a95c8fada716c89d0021"),
ord_dt: ISODate("2012-07-01T04:00:00Z"),
ship_dt: ISODate("2012-07-02T04:00:00Z"),
item:
{
sku: "abc123",
price: 1.99,
uom: "pcs",
qty: 25
}
}
Group by Two Fields The following example groups by the ord_dt and item.sku fields those documents that
have ord_dt greater than 01/01/2012:
db.runCommand(
{
group:
{
ns: 'orders',
key: { ord_dt: 1, 'item.sku': 1 },
cond: { ord_dt: { $gt: new Date( '01/01/2012' ) } },
$reduce: function ( curr, result ) { },
initial: { }
}
}
)
The result is a document that contain the retval field which contains the group by records, the count field which
contains the total number of documents grouped, the keys field which contains the number of unique groupings (i.e.
number of elements in the retval), and the ok field which contains the command status:
{ "retval" :
[ { "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
],
"count" : 13,
"keys" : 11,
"ok" : 1 }
:
:
:
:
:
:
:
:
:
:
:
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-06-01T04:00:00Z"),
ISODate("2012-06-01T04:00:00Z"),
ISODate("2012-06-01T04:00:00Z"),
ISODate("2012-05-01T04:00:00Z"),
ISODate("2012-05-01T04:00:00Z"),
ISODate("2012-06-08T04:00:00Z"),
ISODate("2012-06-08T04:00:00Z"),
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
:
:
:
:
:
:
:
:
:
:
:
"abc123"},
"abc456"},
"bcd123"},
"efg456"},
"abc123"},
"efg456"},
"ijk123"},
"abc123"},
"abc456"},
"abc123"},
"abc456"}
The method call is analogous to the SQL statement:
218
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
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 item.sku fields those documents that
have ord_dt greater than 01/01/2012 and calculates the sum of the qty field for each grouping:
db.runCommand(
{ group:
{
ns: 'orders',
key: { ord_dt: 1, 'item.sku': 1 },
cond: { ord_dt: { $gt: new Date( '01/01/2012' ) } },
$reduce: function ( curr, result ) {
result.total += curr.item.qty;
},
initial: { total : 0 }
}
}
)
The retval field of the returned document is an array of documents that contain the group by fields and the calculated
aggregation field:
{ "retval" :
[ { "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
{ "ord_dt"
],
"count" : 13,
"keys" : 11,
"ok" : 1 }
:
:
:
:
:
:
:
:
:
:
:
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-07-01T04:00:00Z"),
ISODate("2012-06-01T04:00:00Z"),
ISODate("2012-06-01T04:00:00Z"),
ISODate("2012-06-01T04:00:00Z"),
ISODate("2012-05-01T04:00:00Z"),
ISODate("2012-05-01T04:00:00Z"),
ISODate("2012-06-08T04:00:00Z"),
ISODate("2012-06-08T04:00:00Z"),
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
"item.sku"
:
:
:
:
:
:
:
:
:
:
:
"abc123",
"abc456",
"bcd123",
"efg456",
"abc123",
"efg456",
"ijk123",
"abc123",
"abc456",
"abc123",
"abc456",
"total"
"total"
"total"
"total"
"total"
"total"
"total"
"total"
"total"
"total"
"total"
:
:
:
:
:
:
:
:
:
:
:
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/2012 and calculates the sum, count, and average of the qty field
for each grouping:
db.runCommand(
{
group:
{
2.2. Database Commands
219
25
25
10
10
25
15
20
45
25
25
25
},
},
},
},
},
},
},
},
},
},
}
MongoDB Reference Manual, Release 2.8.0-rc3
ns: 'orders',
$keyf: function(doc) {
return { day_of_week: doc.ord_dt.getDay() };
},
cond: { ord_dt: { $gt: new Date( '01/01/2012' ) } },
$reduce: function( curr, result ) {
result.total += curr.item.qty;
result.count++;
},
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];
result.avg = Math.round(result.total / result.count);
}
}
}
)
The retval field of the returned document is an array of documents that contain the group by fields and the calculated
aggregation field:
{
"retval" :
[
{ "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 }
],
"count" : 13,
"keys" : 3,
"ok" : 1
}
See also:
http://docs.mongodb.org/manual/core/aggregation
mapReduce
mapReduce
The mapReduce (page 220) command allows you to run map-reduce aggregation operations over a collection.
The mapReduce (page 220) command has the following prototype form:
db.runCommand(
{
mapReduce: <collection>,
map: <function>,
reduce: <function>,
finalize: <function>,
out: <output>,
query: <document>,
sort: <document>,
limit: <number>,
scope: <document>,
220
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
jsMode: <boolean>,
verbose: <boolean>
}
)
Pass the name of the collection to the mapReduce command (i.e. <collection>) to use as the source
documents to perform the map reduce operation. The command also accepts the following parameters:
field collection mapReduce The name of the collection on which you want to perform map-reduce.
This collection will be filtered using query before being processed by the map function.
field Javascript 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 223) for more information.
field JavaScript 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 223) for more information.
field string or document out Specifies where to output the result of the map-reduce operation. You
can either output to a collection or return the result inline. On a primary member of a replica set
you can output either to a collection or inline, but on a secondary, only inline output is possible.
See out Options (page 224) for more information.
field document query Specifies the selection criteria using query operators (page 400) for determining 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 Javascript function finalize Follows the reduce method and modifies the output.
See Requirements for the finalize Function (page 224) 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:
• 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 storage. 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 mapper’s emit() function.
2.2. Database Commands
221
MongoDB Reference Manual, Release 2.8.0-rc3
The jsMode defaults to false.
field Boolean verbose Specifies whether to include the timing information in the result information. The verbose defaults to true to include the timing information.
The following is a prototype usage of the mapReduce (page 220) command:
var mapFunction = function() { ... };
var reduceFunction = function(key, values) { ... };
db.runCommand(
{
mapReduce: <input-collection>,
map: mapFunction,
reduce: reduceFunction,
out: { merge: <output-collection> },
query: <query>
}
)
JavaScript in MongoDB
Although mapReduce (page 220) uses JavaScript, most interactions with MongoDB do not use JavaScript but
use an idiomatic driver in the language of the interacting application.
Note: Changed in version 2.4.
In MongoDB 2.4, map-reduce operations (page 220), the group (page 216) command, and $where
(page 421) operator expressions cannot access certain global functions or properties, such as db, that are available in
the mongo (page 610) shell.
When upgrading to MongoDB 2.4, you will need to refactor your code if your map-reduce operations
(page 220), group (page 216) commands, or $where (page 421) 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 220), the
group (page 216) command, and $where (page 421) operator expressions in MongoDB 2.4:
Available Properties
Available Functions
args
MaxKey
MinKey
assert()
BinData()
DBPointer()
DBRef()
doassert()
emit()
gc()
HexData()
hex_md5()
isNumber()
isObject()
ISODate()
isString()
222
Map()
MD5()
NumberInt()
NumberLong()
ObjectId()
print()
printjson()
printjsononeline()
sleep()
Timestamp()
tojson()
tojsononeline()
tojsonObject()
UUID()
version()
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
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:
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 MongoDB’s maximum BSON document size (page 692).
• 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
document’s status field:
function() {
if (this.status == '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 document’s items field:
function() {
this.items.forEach(function(item){ emit(item.sku, 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.
2.2. Database Commands
223
MongoDB Reference Manual, Release 2.8.0-rc3
• The inputs to reduce must not be larger than half of MongoDB’s maximum BSON document size (page 692).
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:
• 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 ] )
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.
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:
224
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
– replace
Replace the contents of the <collectionName> if the collection with the <collectionName> exists.
– 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.
• 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 692).
Map-Reduce Examples In the mongo (page 610) shell, the db.collection.mapReduce() (page 58)
method is a wrapper around the mapReduce (page 220) command.
The following examples use the
db.collection.mapReduce() (page 58) method:
Consider the following map-reduce operations on a collection orders that contains documents 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 } ]
}
2.2. Database Commands
225
MongoDB Reference Manual, Release 2.8.0-rc3
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.
var mapFunction1 = function() {
emit(this.cust_id, this.price);
};
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 Array.sum(valuesPrices);
};
3. Perform the map-reduce on all documents in the orders collection using the mapFunction1 map function
and the reduceFunction1 reduce function.
db.orders.mapReduce(
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 results 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 item.sku 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 < this.items.length; idx++) {
var key = this.items[idx].sku;
var value = {
count: 1,
qty: this.items[idx].qty
};
emit(key, value);
}
};
226
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
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.
• In reducedVal, the count field contains the sum of the count fields from the individual array elements, 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 < countObjVals.length; idx++) {
reducedVal.count += countObjVals[idx].count;
reducedVal.qty += 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) {
reducedVal.avg = reducedVal.qty/reducedVal.count;
return reducedVal;
};
4. Perform the map-reduce operation on the orders collection
reduceFunction2, and finalizeFunction2 functions.
using
the
mapFunction2,
db.orders.mapReduce( 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.
For more information and examples, see the Map-Reduce page and http://docs.mongodb.org/manual/tutorial/perfo
Output If you set the out (page 224) parameter to write the results to a collection, the mapReduce (page 220)
command returns a document in the following form:
{
"result" : <string or document>,
"timeMillis" : <int>,
2.2. Database Commands
227
MongoDB Reference Manual, Release 2.8.0-rc3
"counts" : {
"input" : <int>,
"emit" : <int>,
"reduce" : <int>,
"output" : <int>
},
"ok" : <int>,
}
If you set the out (page 224) parameter to output the results inline, the mapReduce (page 220) command returns a
document in the following form:
{
"results" : [
{
"_id" : <key>,
"value" :<reduced or finalizedValue for key>
},
...
],
"timeMillis" : <int>,
"counts" : {
"input" : <int>,
"emit" : <int>,
"reduce" : <int>,
"output" : <int>
},
"ok" : <int>
}
mapReduce.result
For output sent to a collection, this value is either:
•a string for the collection name if out (page 224) did not specify the database name, or
•a document with both db and collection fields if out (page 224) specified both a database and collection name.
mapReduce.results
For output written inline, an array of resulting documents. Each resulting document contains two fields:
•_id field contains the key value,
•value field contains the reduced or finalized value for the associated key.
mapReduce.timeMillis
The command execution time in milliseconds.
mapReduce.counts
Various count statistics from the mapReduce (page 220) command.
mapReduce.counts.input
The number of documents the mapReduce (page 220) command called the map function.
mapReduce.counts.emit
The number of times the mapReduce (page 220) command called the emit function.
mapReduce.counts.reduce
The number of times the mapReduce (page 220) command called the reduce function.
mapReduce.counts.output
The number of output values produced.
228
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
mapReduce.ok
A value of 1 indicates the mapReduce (page 220) command ran successfully. A value of 0 indicates an error.
Additional Information
• http://docs.mongodb.org/manual/tutorial/troubleshoot-map-function
• http://docs.mongodb.org/manual/tutorial/troubleshoot-reduce-function
• db.collection.mapReduce() (page 58)
• http://docs.mongodb.org/manual/core/aggregation
For a detailed comparison of the different approaches, see Aggregation Commands Comparison (page 569).
Geospatial Commands
Geospatial Commands
Name
geoNear (page 229)
geoSearch (page 233)
geoWalk (page 233)
Description
Performs a geospatial query that returns the documents closest to a given point.
Performs a geospatial query that uses MongoDB’s haystack index functionality.
An internal command to support geospatial queries.
geoNear
Definition
geoNear
Specifies a point for which a geospatial query returns the closest documents first. The query returns the documents from nearest to farthest. The geoNear (page 229) command provides an alternative to the $near
(page 429) operator. In addition to the functionality of $near (page 429), geoNear (page 229) returns additional diagnostic information.
The geoNear (page 229) command accepts a document that contains the following fields. Specify all distances
in the same units as the document coordinate system:
field string geoNear The collection to query.
:field GeoJSON point,:term:legacy coordinate pairs <legacy coordinate pairs> near:
The point for which to find the closest documents.
field number limit The maximum number of documents to return. The default value is 100. See
also the num option.
field number num The num option provides the same function as the limit option. Both define
the maximum number of documents to return. If both options are included, the num value
overrides the limit value.
field number minDistance The minimum distance from the center point that the documents must
be. MongoDB filters the results to those documents that are at least the specified distance from
the center point.
Only available for use with 2dsphere index.
Specify the distance in meters for GeoJSON data and in radians for legacy coordinate pairs.
New in version 2.6.
2.2. Database Commands
229
MongoDB Reference Manual, Release 2.8.0-rc3
field number maxDistance The maximum distance from the center point that the documents can
be. MongoDB limits the results to those documents that fall within the specified distance from
the center point.
Specify the distance in meters for GeoJSON data and in radians for legacy coordinate pairs.
field document query Limits the results to the documents that match the query. The query syntax
is the usual MongoDB read operation query syntax.
You cannot specify a $near (page 429) predicate in the query field of the geoNear
(page 229) command.
field Boolean spherical Required if using a 2dsphere index. For use with 2dsphere indexes,
spherical must be true.
The default value is false.
field number distanceMultiplier The factor to multiply all distances returned by the query. For
example, use the distanceMultiplier to convert radians, as returned by a spherical query,
to kilometers by multiplying by the radius of the Earth.
field Boolean includeLocs If this is true, the query returns the location of the matching documents
in the results. The default is false. This option is useful when a location field contains multiple
locations. To specify a field within a subdocument, use dot notation.
field Boolean uniqueDocs If this value is true, the query returns a matching document once, even
if more than one of the document’s location fields match the query.
Deprecated since version 2.6: Geospatial queries no longer return duplicate results. The
$uniqueDocs (page 437) operator has no impact on results.
Considerations The geoNear (page 229) command can use either a GeoJSON point or legacy coordinate pairs.
The geoNear (page 229) command requires that a collection have at most only one 2d index and/or only one
2dsphere.
You cannot specify a $near (page 429) predicate in the query field of the geoNear (page 229) command.
Behavior geoNear (page 229) always returns the documents sorted by distance. Any other sort order requires
to sort the documents in memory, which can be inefficient. To return results in a different sort order, use the
$geoWithin operator and the sort() method.
Because geoNear (page 229) orders the documents from nearest to farthest, the minDistance field effectively
skips over the first n documents where n is determined by the distance requirement.
Command Format
2dsphere Index To query a 2dsphere index, use the following syntax:
db.runCommand( {
geoNear: <collection> ,
near: { type: "Point" , coordinates: [ <coordinates> ] } ,
spherical: true,
...
} )
You must include spherical:
230
true.
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
2d Index To query a 2d index, use:
db.runCommand( {
geoNear: <collection>,
near : [ <coordinates> ],
...
} )
Examples The following examples run the geoNear (page 229) command on the collection places that has a
2dsphere index.
Specify a Query Condition The following geoNear (page 229) command queries for documents whose
category equals "public" and returns the matching documents in order of nearest to farthest to the specified
point:
db.runCommand(
{
geoNear: "places",
near: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
spherical: true,
query: { category: "public" }
}
)
The operation returns the following output, the documents in the results from nearest to farthest:
{
"results" : [
{
"dis" : 0,
"obj" : {
"_id" : 2,
"location" : { "type" : "Point", "coordinates" : [ -73.9667, 40.78 ] },
"name" : "Central Park",
"category" : "public"
}
},
{
"dis" : 3245.988787957091,
"obj" : {
"_id" : 3,
"location" : { "type" : "Point", "coordinates" : [ -73.9836, 40.7538 ] },
"name" : "Bryant Park",
"category" : "public"
}
},
{
"dis" : 7106.506152782733,
"obj" : {
"_id" : 4,
"location" : { "type" : "Point", "coordinates" : [ -73.9928, 40.7193 ] },
"name" : "Sara D. Roosevelt Park",
"category" : "public"
}
},
],
2.2. Database Commands
231
MongoDB Reference Manual, Release 2.8.0-rc3
"stats" : {
"nscanned" : NumberLong(47),
"objectsLoaded" : NumberLong(47),
"avgDistance" : 3450.8316469132747,
"maxDistance" : 7106.506152782733,
"time" : 4
},
"ok" : 1
}
Specify a minDistance and maxDistance The following example specifies a minDistance of 3000 meters
and maxDistance of 7000 meters:
db.runCommand(
{
geoNear: "places",
near: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
spherical: true,
query: { category: "public" },
minDistance: 3000,
maxDistance: 7000
}
)
The operation returns the following output:
{
"results" : [
{
"dis" : 3245.988787957091,
"obj" : {
"_id" : 3,
"location" : { "type" : "Point", "coordinates" : [ -73.9836, 40.7538 ] },
"name" : "Bryant Park",
"category" : "public"
}
}
],
"stats" : {
"nscanned" : NumberLong(11),
"objectsLoaded" : NumberLong(11),
"avgDistance" : 3245.988787957091,
"maxDistance" : 3245.988787957091,
"time" : 0
},
"ok" : 1
}
Output The geoNear (page 229) command returns a document with the following fields:
geoNear.results
An array with the results of the geoNear (page 229) command, sorted by distance with the nearest result listed
first and farthest last.
geoNear.results[n].dis
For each document in the results, the distance from the coordinates defined in the geoNear (page 229) command.
232
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
geoNear.results[n].obj
The document from the collection.
geoNear.stats
An object with statistics about the query used to return the results of the geoNear (page 229) search.
geoNear.stats.nscanned
The total number of index entries scanned during the database operation.
geoNear.stats.objectsLoaded
The total number of documents read from disk during the database operation.
geoNear.stats.avgDistance
The average distance between the coordinates defined in the geoNear (page 229) command and coordinates
of the documents returned as results.
geoNear.stats.maxDistance
The maximum distance between the coordinates defined in the geoNear (page 229) command and coordinates
of the documents returned as results.
geoNear.stats.time
The execution time of the database operation, in milliseconds.
geoNear.ok
A value of 1 indicates the geoNear (page 229) search succeeded. A value of 0 indicates an error.
geoSearch
geoSearch
The geoSearch (page 233) command provides an interface to MongoDB’s haystack index functionality. These
indexes are useful for returning results based on location coordinates after collecting results based on some other
query (i.e. a “haystack.”) Consider the following example:
{ geoSearch : "places", near : [33, 33], maxDistance : 6, search : { type : "restaurant" }, limi
The above command returns all documents with a type of restaurant having a maximum distance of 6
units from the coordinates [30,33] in the collection places up to a maximum of 30 results.
Unless specified otherwise, the geoSearch (page 233) command limits results to 50 documents.
Important: geoSearch (page 233) is not supported for sharded clusters.
geoWalk
geoWalk
geoWalk (page 233) is an internal command.
2.2. Database Commands
233
MongoDB Reference Manual, Release 2.8.0-rc3
Query and Write Operation Commands
Query and Write Operation Commands
Name
delete (page 234)
eval (page 237)
findAndModify (page 239)
getLastError (page 245)
getPrevError (page 247)
insert (page 247)
parallelCollectionScan
(page 249)
resetError (page 250)
text (page 251)
update (page 251)
Description
Deletes one or more documents.
Runs a JavaScript function on the database server.
Returns and modifies a single document.
Returns the success status of the last operation.
Returns status document containing all errors since the last resetError
(page 250) command.
Inserts one or more documents.
Lets applications use multiple parallel cursors when reading documents
from a collection.
Resets the last error status.
Performs a text search.
Updates one or more documents.
delete
Definition
delete
New in version 2.6.
The delete (page 234) command removes documents from a collection. A single delete (page 234) command can contain multiple delete specifications. The command cannot operate on capped collections.
The remove methods provided by the MongoDB drivers use this command internally.
The delete (page 234) command has the following syntax:
{
delete: <collection>,
deletes: [
{ q : <query>, limit : <integer> },
{ q : <query>, limit : <integer> },
{ q : <query>, limit : <integer> },
...
],
ordered: <boolean>,
writeConcern: { <write concern> }
}
The command takes the following fields:
field string delete The name of the target collection.
field array deletes An array of one or more delete statements to perform in the named collection.
field boolean ordered If true, then when a delete statement fails, return without performing the
remaining delete statements. If false, then when a delete statement fails, continue with the
remaining delete statements, if any. Defaults to true.
field document writeConcern A document expressing the write concern of the delete
(page 234) command. Omit to use the default write concern.
Each element of the deletes array contains the following sub-fields:
field document q The query that matches documents to delete.
234
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
field integer limit The number of matching documents to delete. Specify either a 0 to delete all
matching documents or 1 to delete a single document.
Returns A document that contains the status of the operation. See Output (page 236) for details.
Behavior The total size of all the queries (i.e. the q field values) in the deletes array must be less than or equal
to the maximum BSON document size (page 692).
The total number of delete documents in the deletes array must be less than or equal to the maximum bulk
size.
Examples
Limit the Number of Documents Deleted The following example deletes from the orders collection one document that has the status equal to D by specifying the limit of 1:
db.runCommand(
{
delete: "orders",
deletes: [ { q: { status: "D" }, limit: 1 } ]
}
)
The returned document shows that the command deleted 1 document. See Output (page 236) for details.
{ "ok" : 1, "n" : 1 }
Delete All Documents That Match a Condition The following example deletes from the orders collection all
documents that have the status equal to D by specifying the limit of 0:
db.runCommand(
{
delete: "orders",
deletes: [ { q: { status: "D" }, limit: 0 } ],
writeConcern: { w: "majority", wtimeout: 5000 }
}
)
The returned document shows that the command found and deleted 13 documents. See Output (page 236) for details.
{ "ok" : 1, "n" : 13 }
Delete All Documents from a Collection
query condition and a limit of 0:
Delete all documents in the orders collection by specifying an empty
db.runCommand(
{
delete: "orders",
deletes: [ { q: { }, limit: 0 } ],
writeConcern: { w: "majority", wtimeout: 5000 }
}
)
The returned document shows that the command found and deleted 35 documents in total. See Output (page 236) for
details.
2.2. Database Commands
235
MongoDB Reference Manual, Release 2.8.0-rc3
{ "ok" : 1, "n" : 35 }
Bulk Delete The following example performs multiple delete operations on the orders collection:
db.runCommand(
{
delete: "orders",
deletes: [
{ q: { status: "D" }, limit: 0 },
{ q: { cust_num: 99999, item: "abc123", status: "A" }, limit: 1 }
],
ordered: false,
writeConcern: { w: 1 }
}
)
The returned document shows that the command found and deleted 21 documents in total for the two delete statements.
See Output (page 236) for details.
{ "ok" : 1, "n" : 21 }
Output The returned document contains a subset of the following fields:
delete.ok
The status of the command.
delete.n
The number of documents deleted.
delete.writeErrors
An array of documents that contains information regarding any error encountered during the delete operation.
The writeErrors (page 236) array contains an error document for each delete statement that errors.
Each error document contains the following information:
delete.writeErrors.index
An integer that identifies the delete statement in the deletes array, which uses a zero-based index.
delete.writeErrors.code
An integer value identifying the error.
delete.writeErrors.errmsg
A description of the error.
delete.writeConcernError
Document that describe error related to write concern and contains the field:
delete.writeConcernError.code
An integer value identifying the cause of the write concern error.
delete.writeConcernError.errmsg
A description of the cause of the write concern error.
The following is an example document returned for a successful delete (page 234) command:
{ ok: 1, n: 1 }
The following is an example document returned for a delete (page 234) command that encountered an error:
236
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
{
"ok" : 1,
"n" : 0,
"writeErrors" : [
{
"index" : 0,
"code" : 10101,
"errmsg" : "can't remove from a capped collection: test.cappedLog"
}
]
}
eval
eval
The eval (page 237) command evaluates JavaScript functions on the database server.
The eval (page 237) command has the following form:
{
eval: <function>,
args: [ <arg1>, <arg2> ... ],
nolock: <boolean>
}
The command contains the following fields:
field function eval A JavaScript function.
field array args An array of arguments to pass to the JavaScript function. Omit if the function does
not take arguments.
field boolean nolock By default, eval (page 237) takes a global write lock before evaluating the
JavaScript function. As a result, eval (page 237) blocks all other read and write operations to
the database while the eval (page 237) operation runs. Set nolock to true on the eval
(page 237) command to prevent the eval (page 237) command from taking the global write
lock before evaluating the JavaScript. nolock does not impact whether operations within the
JavaScript code itself takes a write lock.
JavaScript in MongoDB
Although eval (page 237) uses JavaScript, most interactions with MongoDB do not use JavaScript but use an
idiomatic driver in the language of the interacting application.
Behavior
Write Lock By default, eval (page 237) takes a global write lock while evaluating the JavaScript function. As a
result, eval (page 237) blocks all other read and write operations to the database while the eval (page 237) operation
runs.
To prevent the taking of the global write lock while evaluating the JavaScript code, use the eval (page 237) command
with nolock set to true. nolock does not impact whether the operations within the JavaScript code take write
locks.
For long running eval (page 237) operation, consider using either the eval command with nolock:
using other server side code execution options.
2.2. Database Commands
true or
237
MongoDB Reference Manual, Release 2.8.0-rc3
Sharded Data You can not use eval (page 237) with sharded collections. In general, you should avoid using eval
(page 237) in sharded clusters; nevertheless, it is possible to use eval (page 237) 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 237).
Providing such access is not recommended, but if your organization requires a user to run eval (page 237), 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, eval (page 237) executed in a single thread.
Example The following example uses eval (page 237) to perform an increment and calculate the average on the
server:
db.runCommand( {
eval: function(name, incAmount) {
var doc = db.myCollection.findOne( { name : name } );
doc = doc || { name : name , num : 0 , total : 0 , avg : 0 };
doc.num++;
doc.total += incAmount;
doc.avg = doc.total / doc.num;
db.myCollection.save( doc );
return doc;
},
args: [ "eliot", 5 ]
}
);
The db in the function refers to the current database.
The mongo (page 610) shell provides a helper method db.eval() (page 112) 13 , so you can express the above as
follows:
db.eval( function(name, incAmount) {
var doc = db.myCollection.findOne( { name : name } );
doc = doc || { name : name , num : 0 , total : 0 , avg : 0 };
doc.num++;
doc.total += incAmount;
doc.avg = doc.total / doc.num;
db.myCollection.save( doc );
return doc;
},
"eliot", 5 );
13 The helper db.eval() (page 112) in the mongo (page 610) shell wraps the eval (page 237) command. Therefore, the helper method shares
the characteristics and behavior of the underlying command with one exception: db.eval() (page 112) method does not support the nolock
option.
238
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
If you want to use the server’s interpreter, you must run eval (page 237). Otherwise, the mongo (page 610) shell’s
JavaScript interpreter evaluates functions entered directly into the shell.
If an error occurs, eval (page 237) throws an exception. The following invalid function uses the variable x without
declaring it as an argument:
db.runCommand(
{
eval: function() { return x + x; },
args: [ 3 ]
}
)
The statement will result in the following exception:
{
"errmsg" : "exception: JavaScript execution failed: ReferenceError: x is not defined near '{ retur
"code" : 16722,
"ok" : 0
}
See also:
http://docs.mongodb.org/manual/core/server-side-javascript
findAndModify
Definition
findAndModify
The findAndModify (page 239) command 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 command has the following syntax:
{
findAndModify: <collection-name>,
query: <document>,
sort: <document>,
remove: <boolean>,
update: <document>,
new: <boolean>,
fields: <document>,
upsert: <boolean>
}
The findAndModify (page 239) command takes the following fields:
field string findAndModify The collection against which to run the command.
param document query The selection criteria for the modification. The query field employs the
same query selectors (page 400) as used in the db.collection.find() (page 36) method.
Although the query may match multiple documents, findAndModify (page 239) will only
select one document to modify.
param document sort Determines which document the operation modifies if the query selects multiple documents. findAndModify (page 239) modifies the first document in the sort order
specified by this argument.
2.2. Database Commands
239
MongoDB Reference Manual, Release 2.8.0-rc3
param Boolean remove Must specify either the remove or the update field. Removes the document 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 update of the selected document. The update field employs the same update operators (page 451)
or field: value specifications to modify the selected document.
param Boolean new When true, returns the modified document rather than the original. The
findAndModify (page 239) method ignores the new option for remove operations. The
default is false.
param document fields 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 Used in conjunction with the update field.
When true, findAndModify (page 239) creates a new document if no document matches
the query, or if documents match the query, findAndModify (page 239) performs an
update. To avoid multiple upserts, ensure that the query fields are uniquely indexed.
The default is false.
Output The return document contains the following fields:
• The lastErrorObject field that returns the details of the command:
– The updatedExisting field only appears if the command specifies an update or an update with
upsert: true; i.e. the field does not appear for a remove.
– The upserted field only appears if the update with the upsert:
insertion.
true operation results in an
• The value field that returns either:
– the original (i.e. pre-modification) document if new is false, or
– the modified or inserted document if new:
true.
• The ok field that returns the status of the command.
Note: If the findAndModify (page 239) finds no matching document, then:
• for update or remove operations, lastErrorObject does not appear in the return document and the
value field holds a null.
{ "value" : null, "ok" : 1 }
• for update with upsert: true operation that results in an insertion, if the command also specifies new
is false and specifies a sort, the return document has a lastErrorObject, value, and ok fields, but
the value field holds an empty document {}.
• for update with upsert: true operation that results in an insertion, if the command also specifies new is
false but does not specify a sort, the return document has a lastErrorObject, value, and ok fields,
but the value field holds a null.
Behavior
240
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Upsert and Unique Index When the findAndModify (page 239) command includes the upsert: true
option and the query field(s) is not uniquely indexed, the command could insert a document multiple times in certain
circumstances.
Consider an example where no document with the name Andy exists and multiple clients issue the following command:
db.runCommand(
{
findAndModify: "people",
query: { name: "Andy" },
sort: { rating: 1 },
update: { $inc: { score: 1 } },
upsert: true
}
)
If all the commands finish the query phase before any command starts the modify phase, and there is no unique
index on the name field, the commands may each 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, then the multiple findAndModify (page 239) commands will exhibit one of the following behaviors:
• Exactly one findAndModify (page 239) successfully inserts a new document.
• Zero or more findAndModify (page 239) commands update the newly inserted document.
• Zero or more findAndModify (page 239) commands fail when they attempt to insert a duplicate. If the
command fails due to a unique index constraint violation, you can retry the command. Absent a delete of the
document, the retry should not fail.
Sharded Collections When using findAndModify (page 239) in a sharded environment, the query must contain the shard key for all operations against the shard cluster. findAndModify (page 239) operations issued against
mongos (page 601) instances for non-sharded collections function normally.
Concurrency This command obtains a write lock on the affected database and will block other operations until it
has completed; however, typically the write lock is short lived and equivalent to other similar update() (page 72)
operations.
Comparisons with the update Method When updating a document, findAndModify (page 239) and the
update() (page 72) method operate differently:
• By default, both operations modify a single document. However, the update() (page 72) method with its
multi option can modify more than one document.
• If multiple documents match the update criteria, for findAndModify (page 239), you can specify a sort to
provide some measure of control on which document to update.
With the default behavior of the update() (page 72) method, you cannot specify which single document to
update when multiple documents match.
• By default, findAndModify (page 239) method returns an object that contains the pre-modified version of
the document, as well as the status of the operation. To obtain the updated document, use the new option.
The update() (page 72) method returns a WriteResult (page 201) object that contains the status of the
operation. To return the updated document, use the find() (page 36) method. However, other updates may
have modified the document between your update and the document retrieval. Also, if the update modified only
2.2. Database Commands
241
MongoDB Reference Manual, Release 2.8.0-rc3
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 239) to override the default write concern
whereas, starting in MongoDB 2.6, you can specify a write concern to the update() (page 72) method.
When
modifying
a
single
document,
both
findAndModify
(page
239)
and
the
update()
(page
72)
method
atomically
update
the
document.
See
http://docs.mongodb.org/manual/core/write-operations-atomicity for more details
about interactions and order of operations of these methods.
Examples
Update and Return The following command updates an existing document in the people collection where the
document matches the query criteria:
db.runCommand(
{
findAndModify: "people",
query: { name: "Tom", state: "active", rating: { $gt: 10 } },
sort: { rating: 1 },
update: { $inc: { score: 1 } }
}
)
This command 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 command 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 command returns a document with the following fields:
• The lastErrorObject field that contains the details of the command, including the field
updatedExisting which is true, and
• The value field that contains the original (i.e. pre-modification) document selected for this update:
{
"lastErrorObject" : {
"updatedExisting" : true,
"n" : 1,
"connectionId" : 1,
"err" : null,
"ok" : 1
},
"value" : {
"_id" : ObjectId("50f1d54e9beb36a0f45c6452"),
"name" : "Tom",
"state" : "active",
"rating" : 100,
"score" : 5
},
"ok" : 1
}
242
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
To return the modified document in the value field, add the new:true option to the command.
If no document match the query condition, the command returns a document that contains null in the value field:
{ "value" : null, "ok" : 1 }
The mongo (page 610) shell and many drivers provide a findAndModify() (page 42) helper method. Using the
shell helper, this previous operation can take the following form:
db.people.findAndModify( {
query: { name: "Tom", state: "active", rating: { $gt: 10 } },
sort: { rating: 1 },
update: { $inc: { score: 1 } }
} );
However, the findAndModify() (page 42) shell helper method returns only the unmodified document, or if new
is true, the modified document.
{
"_id" : ObjectId("50f1d54e9beb36a0f45c6452"),
"name" : "Tom",
"state" : "active",
"rating" : 100,
"score" : 5
}
upsert: true The following findAndModify (page 239) command 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:
db.runCommand(
{
findAndModify: "people",
query: { name: "Gus", state: "active", rating: 100 },
sort: { rating: 1 },
update: { $inc: { score: 1 } },
upsert: true
}
)
If the command finds a matching document, the command performs an update.
If the command does not find a matching document, the update with upsert: true operation results in an insertion
and returns a document with the following fields:
• The lastErrorObject field that contains the details of the command, including the field upserted that
contains the ObjectId of the newly inserted document, and
• The value field that contains an empty document {} as the original document because the command included
the sort option:
{
"lastErrorObject" : {
"updatedExisting" : false,
"upserted" : ObjectId("50f2329d0092b46dae1dc98e"),
"n" : 1,
"connectionId" : 1,
"err" : null,
"ok" : 1
},
2.2. Database Commands
243
MongoDB Reference Manual, Release 2.8.0-rc3
"value" : {
},
"ok" : 1
}
If the command did not include the sort option, the value field would contain null:
{
"value" : null,
"lastErrorObject" : {
"updatedExisting" : false,
"n" : 1,
"upserted" : ObjectId("5102f7540cb5c8be998c2e99")
},
"ok" : 1
}
Return New Document The following findAndModify (page 239) command includes both upsert: true
option and the new:true option. The command 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:
db.runCommand(
{
findAndModify: "people",
query: { name: "Pascal", state: "active", rating: 25 },
sort: { rating: 1 },
update: { $inc: { score: 1 } },
upsert: true,
new: true
}
)
The command returns the newly inserted document in the value field:
{
"lastErrorObject" : {
"updatedExisting" : false,
"upserted" : ObjectId("50f47909444c11ac2448a5ce"),
"n" : 1,
"connectionId" : 1,
"err" : null,
"ok" : 1
},
"value" : {
"_id" : ObjectId("50f47909444c11ac2448a5ce"),
"name" : "Pascal",
"rating" : 25,
"score" : 1,
"state" : "active"
},
"ok" : 1
}
244
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
getLastError
Definition
getLastError
Changed in version 2.6: A new protocol for write operations (page 745) integrates write concerns with the write
operations, eliminating the need for a separate getLastError (page 245) command. Write methods now
return the status of the write operation, including error information.
In previous versions, clients typically used the getLastError (page 245) command in combination with the
write operations to ensure that the write succeeds.
Returns the error status of the preceding write operation on the current connection.
getLastError (page 245) uses the following prototype form:
{ getLastError: 1 }
getLastError (page 245) uses the following fields:
field Boolean j If true, wait for the next journal commit before returning, rather than waiting for
a full disk flush. If mongod (page 583) does not have journaling enabled, this option has no
effect. If this option is enabled for a write operation, mongod (page 583) will wait no more than
1/3 of the current commitIntervalMs before writing data to the journal.
field integer,string w When running with replication, this is the number of servers to replicate to
before returning. A w value of 1 indicates the primary only. A w value of 2 includes the primary
and at least one secondary, etc. In place of a number, you may also set w to majority to
indicate that the command should wait until the latest write propagates to a majority of replica
set members. If using w, you should also use wtimeout. Specifying a value for w without also
providing a wtimeout may cause getLastError (page 245) to block indefinitely.
field Boolean fsync If true, wait for mongod (page 583) to write this data to disk before returning.
Defaults to false. In most cases, use the j option to ensure durability and consistency of the data
set.
field integer wtimeout Milliseconds. Specify a value in milliseconds to control how long to wait
for write propagation to complete. If replication does not complete in the given timeframe, the
getLastError (page 245) command will return with an error status.
See also:
Write Concern, http://docs.mongodb.org/manual/reference/write-concern,
replica-set-write-concern.
and
Output Each getLastError() command returns a document containing a subset of the fields listed below.
getLastError.ok
ok (page 245) is true when the getLastError (page 245) command completes successfully.
Note: A value of true does not indicate that the preceding operation did not produce an error.
getLastError.err
err (page 245) is null unless an error occurs. When there was an error with the preceding operation, err
contains a textual description of the error.
getLastError.code
code (page 245) reports the preceding operation’s error code.
2.2. Database Commands
245
MongoDB Reference Manual, Release 2.8.0-rc3
getLastError.connectionId
The identifier of the connection.
getLastError.lastOp
When issued against a replica set member and the preceding operation was a write or update, lastOp
(page 246) is the optime timestamp in the oplog of the change.
getLastError.n
n (page 246) reports the number of documents updated or removed, if the preceding operation was an update or
remove operation.
getLastError.shards
When issued against a sharded cluster after a write operation, shards (page 246) identifies the shards targeted
in the write operation. shards (page 246) is present in the output only if the write operation targets multiple
shards.
getLastError.singleShard
When issued against a sharded cluster after a write operation, identifies the shard targeted in the write operation.
singleShard (page 246) is only present if the write operation targets exactly one shard.
getLastError.updatedExisting
updatedExisting (page 246) is true when an update affects at least one document and does not result in
an upsert.
getLastError.upserted
If the update results in an insert, upserted (page 246) is the value of _id field of the document.
Changed in version 2.6: Earlier versions of MongoDB included upserted (page 246) only if _id was an
ObjectId.
getLastError.wnote
If set, wnote indicates that the preceding operation’s error relates to using the w parameter to getLastError
(page 245).
See
http://docs.mongodb.org/manual/reference/write-concern for more information about w
values.
getLastError.wtimeout
wtimeout (page 246) is true if the getLastError (page 245) timed out because of the wtimeout setting
to getLastError (page 245).
getLastError.waited
If the preceding operation specified a timeout using the wtimeout setting to getLastError (page 245),
then waited (page 246) reports the number of milliseconds getLastError (page 245) waited before timing
out.
getLastError.wtime
getLastError.wtime (page 246) is the number of milliseconds spent waiting for the preceding operation
to complete. If getLastError (page 245) timed out, wtime (page 246) and getLastError.waited are
equal.
Examples
Confirm Replication to Two Replica Set Members The following example ensures the operation has replicated to
two members (the primary and one other member):
246
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.runCommand( { getLastError: 1, w: 2 } )
Confirm Replication to a Majority of a Replica Set The following example ensures the write operation has replicated to a majority of the configured members of the set.
db.runCommand( { getLastError: 1, w: "majority" } )
Changed in version 2.6: In Master/Slave deployments, MongoDB treats w: "majority" as equivalent to w:
1. In earlier versions of MongoDB, w: "majority" produces an error in master/slave deployments.
Set a Timeout for a getLastError Response Unless you specify a timeout, a getLastError (page 245)
command may block forever if MongoDB cannot satisfy the requested write concern. To specify a timeout of 5000
milliseconds, use an invocation that resembles the following:
db.runCommand( { getLastError: 1, w: 2, wtimeout:5000 } )
When wtimeout is 0, the getLastError (page 245) operation will never time out.
getPrevError
getPrevError
The getPrevError (page 247) command returns the errors since the last resetError (page 250) command.
See also:
db.getPrevError() (page 116)
insert
Definition
insert
New in version 2.6.
The insert (page 247) command inserts one or more documents and returns a document containing the status
of all inserts. The insert methods provided by the MongoDB drivers use this command internally.
The command has the following syntax:
{
insert: <collection>,
documents: [ <document>, <document>, <document>, ... ],
ordered: <boolean>,
writeConcern: { <write concern> }
}
The insert (page 247) command takes the following fields:
field string insert The name of the target collection.
field array documents An array of one or more documents to insert into the named collection.
field boolean ordered If true, then when an insert of a document fails, return without inserting
any remaining documents listed in the inserts array. If false, then when an insert of a
document fails, continue to insert the remaining documents. Defaults to true.
2.2. Database Commands
247
MongoDB Reference Manual, Release 2.8.0-rc3
field document writeConcern A document that expresses the write concern of the insert
(page 247) command. Omit to use the default write concern.
Returns A document that contains the status of the operation. See Output (page 248) for details.
Behavior The total size of all the documents array elements must be less than or equal to the maximum BSON
document size (page 692).
The total number of documents in the documents array must be less than or equal to the maximum bulk size.
Examples
Insert a Single Document Insert a document into the users collection:
db.runCommand(
{
insert: "users",
documents: [ { _id: 1, user: "abc123", status: "A" } ]
}
)
The returned document shows that the command successfully inserted a document. See Output (page 248) for details.
{ "ok" : 1, "n" : 1 }
Bulk Insert Insert three documents into the users collection:
db.runCommand(
{
insert: "users",
documents: [
{ _id: 2, user:
{ _id: 3, user:
{ _id: 4, user:
],
ordered: false,
writeConcern: { w:
}
)
"ijk123", status: "A" },
"xyz123", status: "P" },
"mop123", status: "P" }
"majority", wtimeout: 5000 }
The returned document shows that the command successfully inserted the three documents. See Output (page 248) for
details.
{ "ok" : 1, "n" : 3 }
Output The returned document contains a subset of the following fields:
insert.ok
The status of the command.
insert.n
The number of documents inserted.
insert.writeErrors
An array of documents that contains information regarding any error encountered during the insert operation.
The writeErrors (page 248) array contains an error document for each insert that errors.
248
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Each error document contains the following fields:
insert.writeErrors.index
An integer that identifies the document in the documents array, which uses a zero-based index.
insert.writeErrors.code
An integer value identifying the error.
insert.writeErrors.errmsg
A description of the error.
insert.writeConcernError
Document that describe error related to write concern and contains the field:
insert.writeConcernError.code
An integer value identifying the cause of the write concern error.
insert.writeConcernError.errmsg
A description of the cause of the write concern error.
The following is an example document returned for a successful insert (page 247) of a single document:
{ ok: 1, n: 1 }
The following is an example document returned for an insert (page 247) of two documents that successfully inserted
one document but encountered an error with the other document:
{
"ok" : 1,
"n" : 1,
"writeErrors" : [
{
"index" : 1,
"code" : 11000,
"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.user
}
]
}
parallelCollectionScan
parallelCollectionScan
New in version 2.6.
Allows applications to use multiple parallel cursors when reading all the documents from a collection, thereby
increasing throughput. The parallelCollectionScan (page 249) command returns a document that
contains an array of cursor information.
Each cursor provides access to the return of a partial set of documents from a collection. Iterating each cursor
returns every document in the collection. Cursors do not contain the results of the database command. The
result of the database command identifies the cursors, but does not contain or constitute the cursors.
The server may return fewer cursors than requested.
The command has the following syntax:
{
parallelCollectionScan: "<collection>",
numCursors: <integer>
}
The parallelCollectionScan (page 249) command takes the following fields:
2.2. Database Commands
249
MongoDB Reference Manual, Release 2.8.0-rc3
field string parallelCollectionScan The name of the collection.
field integer numCursors The maximum number of cursors to return. Must be between 1 and
10000, inclusive.
Output The parallelCollectionScan (page 249) command returns a document containing the array of cursor information:
{
"cursors" : [
{
"cursor" : {
"firstBatch" : [ ],
"ns" : "<database name>.<collection name>",
"id" : NumberLong("155949257847")
},
"ok" : true
}
],
"ok" : 1
}
parallelCollectionScan.cursors
An array with one or more cursors returned with the command.
parallelCollectionScan.cursors.cursor
For each cursor returned, a document with details about the cursor.
parallelCollectionScan.cursors.cursor.firstBatch
An empty first batch is useful for quickly returning a cursor or failure message without doing significant serverside work. See cursor batches.
parallelCollectionScan.cursors.cursor.ns
The namespace for each cursor.
parallelCollectionScan.cursors.cursor.id
The unique id for each cursor.
parallelCollectionScan.cursors.ok
The status of each cursor returned with the command.
parallelCollectionScan.ok
A value of 1 indicates the parallelCollectionScan (page 249) command succeeded. A value of 0
indicates an error.
resetError
resetError
The resetError (page 250) command resets the last error status.
See also:
db.resetError() (page 123)
text
250
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Definition
text
Deprecated since version 2.6: Use $text (page 417) query operator instead.
For document on the text (page 251), refer to the 2.4 Manual 2.4 Manual14 .
update
Definition
update
New in version 2.6.
The update (page 251) command modifies documents in a collection. A single update (page 251) command can contain multiple update statements. The update methods provided by the MongoDB drivers use this
command internally.
The update (page 251) command has the following syntax:
{
update: <collection>,
updates:
[
{ q: <query>, u:
{ q: <query>, u:
{ q: <query>, u:
...
],
ordered: <boolean>,
writeConcern: { <write
<update>, upsert: <boolean>, multi: <boolean> },
<update>, upsert: <boolean>, multi: <boolean> },
<update>, upsert: <boolean>, multi: <boolean> },
concern> }
}
The command takes the following fields:
field string update The name of the target collection.
field array updates An array of one or more update statements to perform in the named collection.
field boolean ordered If true, then when an update statement fails, return without performing the
remaining update statements. If false, then when an update fails, continue with the remaining
update statements, if any. Defaults to true.
field document writeConcern A document expressing the write concern of the update
(page 251) command. Omit to use the default write concern.
Each element of the updates array contains the following sub-fields:
field string document The query that matches documents to update. Use the same query selectors
(page 400) as used in the find() (page 36) method.
field document u The modifications to apply. For details, see Behaviors (page 252).
field boolean upsert If true, perform an insert if no documents match the query. If both upsert
and multi are true and no documents match the query, the update operation inserts only a
single document.
field boolean multi If true, updates all documents that meet the query criteria. If false, limit
the update to one document that meet the query criteria. Defaults to false.
Returns A document that contains the status of the operation. See Output (page 254) for details.
14 http://docs.mongodb.org/v2.4/reference/command/text
2.2. Database Commands
251
MongoDB Reference Manual, Release 2.8.0-rc3
Behaviors The <update> document can contain either all update operator (page 451) expressions or all
field:value expressions.
Update Operator Expressions If the <update> document contains all update operator (page 451) expressions,
as in:
{
$set: { status: "D" },
$inc: { quantity: 2 }
}
Then, the update (page 251) command updates only the corresponding fields in the document.
Field:
Value Expressions If the <update> document contains only field:value expressions, as in:
{
status: "D",
quantity: 4
}
Then the update (page 251) command replaces the matching document with the update document. The update
(page 251) command can only replace a single matching document; i.e. the multi field cannot be true. The
update (page 251) command does not replace the _id value.
Limits For each update element in the updates array, the sum of the query and the update sizes (i.e. q and u )
must be less than or equal to the maximum BSON document size (page 692).
The total number of update statements in the updates array must be less than or equal to the maximum bulk
size.
Examples
Update Specific Fields of One Document
document.
Use update operators (page 451) to update only the specified fields of a
For example, given a users collection, the following command uses the $set (page 459) and $inc (page 452) operators to modify the status and the points fields respectively of a document where the user equals "abc123":
db.runCommand(
{
update: "users",
updates: [
{
q: { user: "abc123" }, u: { $set: { status: "A" }, $inc: { points: 1 } }
}
],
ordered: false,
writeConcern: { w: "majority", wtimeout: 5000 }
}
)
Because <update> document does not specify the optional multi field, the update only modifies one document,
even if more than one document matches the q match condition.
The returned document shows that the command found and updated a single document. See Output (page 254) for
details.
252
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
{ "ok" : 1, "nModified" : 1, "n" : 1 }
Update Specific Fields of Multiple Documents Use update operators (page 451) to update only the specified fields
of a document, and include the multi field set to true in the update statement.
For example, given a users collection, the following command uses the $set (page 459) and $inc (page 452)
operators to modify the status and the points fields respectively of all documents in the collection:
db.runCommand(
{
update: "users",
updates: [
{ q: { }, u: { $set: { status: "A" }, $inc: { points: 1 } }, multi: true }
],
ordered: false,
writeConcern: { w: "majority", wtimeout: 5000 }
}
)
The update modifies all documents that match the query specified in the q field, namely the empty query which
matches all documents in the collection.
The returned document shows that the command found and updated multiple documents. See Output (page 254) for
details.
{ "ok" : 1, "nModified" : 100, "n" : 100 }
Bulk Update The following example performs multiple update operations on the users collection:
db.runCommand(
{
update: "users",
updates: [
{ q: { status: "P" }, u: { $set: { status: "D" } }, multi: true },
{ q: { _id: 5 }, u: { _id: 5, name: "abc123", status: "A" }, upsert: true }
],
ordered: false,
writeConcern: { w: "majority", wtimeout: 5000 }
}
)
The returned document shows that the command modified 10 documents and inserted a document with the _id value
5. See Output (page 254) for details.
{
"ok" : 1,
"nModified" : 10,
"n" : 11,
"upserted" : [
{
"index" : 1,
"_id" : 5
}
]
}
2.2. Database Commands
253
MongoDB Reference Manual, Release 2.8.0-rc3
Output The returned document contains a subset of the following fields:
update.ok
The status of the command.
update.n
The number of documents selected for update. If the update operation results in no change to the document,
e.g. $set (page 459) expression updates the value to the current value, n (page 254) can be greater than
nModified (page 254).
update.nModified
The number of documents updated. If the update operation results in no change to the document, such as setting
the value of the field to its current value, nModified (page 254) can be less than n (page 254).
update.upserted
An array of documents that contains information for each document inserted through the update with upsert:
true.
Each document contains the following information:
update.upserted.index
An integer that identifies the update with upsert:true statement in the updates array, which uses a
zero-based index.
update.upserted._id
The _id value of the added document.
update.writeErrors
An array of documents that contains information regarding any error encountered during the update operation.
The writeErrors (page 254) array contains an error document for each update statement that errors.
Each error document contains the following fields:
update.writeErrors.index
An integer that identifies the update statement in the updates array, which uses a zero-based index.
update.writeErrors.code
An integer value identifying the error.
update.writeErrors.errmsg
A description of the error.
update.writeConcernError
Document that describe error related to write concern and contains the field:
update.writeConcernError.code
An integer value identifying the cause of the write concern error.
update.writeConcernError.errmsg
A description of the cause of the write concern error.
The following is an example document returned for a successful update (page 251) command that performed an
upsert:
{
"ok" : 1,
"nModified" : 0,
"n" : 1,
"upserted" : [
{
"index" : 0,
"_id" : ObjectId("52ccb2118908ccd753d65882")
}
254
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
]
}
The following is an example document returned for a bulk update involving three update statements, where one update
statement was successful and two other update statements encountered errors:
{
"ok" : 1,
"nModified" : 1,
"n" : 1,
"writeErrors" : [
{
"index" : 1,
"code" : 16837,
"errmsg" : "The _id field cannot be changed from {_id: 1.0} to {_id: 5.0}."
},
{
"index" : 2,
"code" : 16837,
"errmsg" : "The _id field cannot be changed from {_id: 2.0} to {_id: 6.0}."
},
]
}
Query Plan Cache Commands
Query Plan Cache Commands
Name
planCacheClearFilters (page 255)
planCacheClear (page 257)
planCacheListFilters (page 258)
planCacheListPlans (page 259)
planCacheListQueryShapes (page 260)
planCacheSetFilter (page 262)
Description
Clears index filter(s) for a collection.
Removes cached query plan(s) for a collection.
Lists the index filters for a collection.
Displays the cached query plans for the specified query shape.
Displays the query shapes for which cached query plans exist.
Sets an index filter for a collection.
planCacheClearFilters
Definition
planCacheClearFilters
New in version 2.6.
Removes index filters on a collection. Although index filters only exist for the duration of the server process and
do not persist after shutdown, you can also clear existing index filters with the planCacheClearFilters
(page 255) command.
Specify the query shape to remove a specific index filter. Omit the query shape to clear all index filters on a
collection.
The command has the following syntax:
db.runCommand(
{
planCacheClearFilters: <collection>,
query: <query pattern>,
2.2. Database Commands
255
MongoDB Reference Manual, Release 2.8.0-rc3
sort: <sort specification>,
projection: <projection specification>
}
)
The planCacheClearFilters (page 255) command has the following field:
field string planCacheClearFilters The name of the collection.
field document query The query predicate associated with the filter to remove. If omitted, clears
all filters from the collection.
The values in the query predicate are insignificant in determining the query shape, so the
values used in the query need not match the values shown using planCacheListFilters
(page 258).
field document sort The sort associated with the filter to remove, if any.
field document projection The projection associated with the filter to remove, if any.
Required Access A user must have access that includes the planCacheIndexFilter action.
Examples
Clear Specific Index Filter on Collection The orders collection contains the following two filters:
{
"query" : { "status" : "A" },
"sort" : { "ord_date" : -1 },
"projection" : { },
"indexes" : [ { "status" : 1, "cust_id" : 1 } ]
}
{
"query" : { "status" : "A" },
"sort" : { },
"projection" : { },
"indexes" : [ { "status" : 1, "cust_id" : 1 } ]
}
The following command removes the second index filter only:
db.runCommand(
{
planCacheClearFilters: "orders",
query: { "status" : "A" }
}
)
Because the values in the query predicate are insignificant in determining the query shape, the following command
would also remove the second index filter:
db.runCommand(
{
planCacheClearFilters: "orders",
query: { "status" : "P" }
}
)
256
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Clear all Index Filters on a Collection The following example clears all index filters on the orders collection:
db.runCommand(
{
planCacheClearFilters: "orders"
}
)
See also:
planCacheListFilters (page 258), planCacheSetFilter (page 262)
planCacheClear
Definition
planCacheClear
New in version 2.6.
Removes cached query plans for a collection. Specify a query shape to remove cached query plans for that
shape. Omit the query shape to clear all cached query plans.
The command has the following syntax:
db.runCommand(
{
planCacheClear: <collection>,
query: <query>,
sort: <sort>,
projection: <projection>
}
)
The planCacheClear (page 257) command has the following field:
field 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.
field document projection The projection associated with the query shape.
field document sort The sort associated with the query shape.
To see the query shapes for which cached query plans exist, use the planCacheListQueryShapes
(page 260) command.
Required Access On systems running with authorization, a user must have access that includes the
planCacheWrite action.
Examples
Clear Cached Plans for a Query Shape If a collection orders has the following query shape:
{
"query" : { "qty" : { "$gt" : 10 } },
"sort" : { "ord_date" : 1 },
"projection" : { }
}
2.2. Database Commands
257
MongoDB Reference Manual, Release 2.8.0-rc3
The following operation clears the query plan cached for the shape:
db.runCommand(
{
planCacheClear: "orders",
query: { "qty" : { "$gt" : 10 } },
sort: { "ord_date" : 1 }
}
)
Clear All Cached Plans for a Collection The following example clears all the cached query plans for the orders
collection:
db.runCommand(
{
planCacheClear: "orders"
}
)
See also:
• PlanCache.clearPlansByQuery() (page 131)
• PlanCache.clear() (page 130)
planCacheListFilters
Definition
planCacheListFilters
New in version 2.6.
Lists the index filters associated with query shapes for a collection.
The command has the following syntax:
db.runCommand( { planCacheListFilters: <collection> } )
The planCacheListFilters (page 258) command has the following field:
field string planCacheListFilters The name of the collection.
Returns Document listing the index filters. See Output (page 258).
Required Access A user must have access that includes the planCacheIndexFilter action.
Output The planCacheListFilters (page 258) command returns the document with the following form:
{
"filters" : [
{
"query" : <query>
"sort" : <sort>,
"projection" : <projection>,
"indexes" : [
<index1>,
...
258
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
]
},
...
],
"ok" : 1
}
planCacheListFilters.filters
The array of documents that contain the index filter information.
Each document contains the following fields:
planCacheListFilters.filters.query
The query predicate associated with this filter. Although the query (page 259) shows the specific values
used to create the index filter, the values in the predicate are insignificant; i.e. query predicates cover
similar queries that differ only in the values.
For instance, a query (page 259) predicate of { "type":
"A" } covers the following query predicates:
"electronics", "status" :
{ type: "food", status: "A" }
{ type: "utensil", status: "D" }
Together with the sort (page 259) and the projection (page 259), the query (page 259) make up
the query shape for the specified index filter.
planCacheListFilters.filters.sort
The sort associated with this filter. Can be an empty document.
Together with the query (page 259) and the projection (page 259), the sort (page 259) make up
the query shape for the specified index filter.
planCacheListFilters.filters.projection
The projection associated with this filter. Can be an empty document.
Together with the query (page 259) and the sort (page 259), the projection (page 259) make up
the query shape for the specified index filter.
planCacheListFilters.filters.indexes
The array of indexes for this query shape. To choose the optimal query plan, the query optimizer evaluates
only the listed indexes and the collection scan.
planCacheListFilters.ok
The status of the command.
See also:
planCacheClearFilters (page 255), planCacheSetFilter (page 262)
planCacheListPlans
Definition
planCacheListPlans
New in version 2.6.
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 mongo (page 610) shell provides the wrapper PlanCache.getPlansByQuery() (page 132) for this
command.
2.2. Database Commands
259
MongoDB Reference Manual, Release 2.8.0-rc3
The planCacheListPlans (page 259) command has the following syntax:
db.runCommand(
{
planCacheListPlans: <collection>,
query: <query>,
sort: <sort>,
projection: <projection>
}
The planCacheListPlans (page 259) command has the following field:
field 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.
field document projection The projection associated with the query shape.
field document sort The sort associated with the query shape.
To see the query shapes for which cached query plans exist, use the planCacheListQueryShapes
(page 260) command.
Required Access On systems running with authorization, 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:
db.runCommand(
{
planCacheListPlans: "orders",
query: { "qty" : { "$gt" : 10 } },
sort: { "ord_date" : 1 }
}
)
See also:
• planCacheListQueryShapes (page 260)
• PlanCache.getPlansByQuery() (page 132)
• PlanCache.listQueryShapes() (page 133)
planCacheListQueryShapes
Definition
planCacheListQueryShapes
New in version 2.6.
Displays the query shapes for which cached query plans exist for a collection.
260
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
The query optimizer only caches the plans for those query shapes that can have more than one viable plan.
The mongo (page 610) shell provides the wrapper PlanCache.listQueryShapes() (page 133) for this
command.
The command has the following syntax:
db.runCommand(
{
planCacheListQueryShapes: <collection>
}
The planCacheListQueryShapes (page 260) command has the following field:
field string planCacheListQueryShapes The name of the collection.
Returns A document that contains an array of query shapes for which cached query plans exist.
Required Access On systems running with authorization, 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:
db.runCommand(
{
planCacheListQueryShapes: "orders"
}
)
The command returns a document that contains the field shapes that contains 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:
{
"shapes" : [
{
"query" : { "qty" : { "$gt" : 10 } },
"sort" : { "ord_date" : 1 },
"projection" : { }
},
{
"query" : { "$or" : [ { "qty" : { "$gt" : 15 } }, { "status" : "A" } ] },
"sort" : { },
"projection" : { }
},
{
"query" : { "$or" :
[
{ "qty" : { "$gt" : 15 }, "item" : "xyz123" },
{ "status" : "A" }
]
},
"sort" : { },
"projection" : { }
}
],
"ok" : 1
}
See also:
2.2. Database Commands
261
MongoDB Reference Manual, Release 2.8.0-rc3
• PlanCache.listQueryShapes() (page 133)
planCacheSetFilter
Definition
planCacheSetFilter
New in version 2.6.
Set an index filter for a collection. If an index filter already exists for the query shape, the command overrides
the previous index filter.
The command has the following syntax:
db.runCommand(
{
planCacheSetFilter: <collection>,
query: <query>,
sort: <sort>,
projection: <projection>,
indexes: [ <index1>, <index2>, ...]
}
)
The planCacheSetFilter (page 262) command has the following field:
field string planCacheSetFilter The name of the collection.
field document query The query predicate associated with the index filter. Together with the sort
and the projection, the query predicate make up the query shape for the specified index
filter.
Only the structure of the predicate, including the field names, are significant; the values in the
query predicate are insignificant. As such, query predicates cover similar queries that differ only
in the values.
field document sort The sort associated with the filter. Together with the query and the
projection, the sort make up the query shape for the specified index filter.
field document projection The projection associated with the filter. Together with the query and
the sort, the projection make up the query shape for the specified index filter.
field array indexes An array of index specification documents that act as the index filter for the
specified query shape. Because the query optimizer chooses among the collection scan
and these indexes, if the indexes are non-existent, the optimizer will choose the collection scan.
Index filters only exist for the duration of the server process and do not persist after shutdown; however, you can
also clear existing index filters using the planCacheClearFilters (page 255) command.
Required Access A user must have access that includes the planCacheIndexFilter action.
Examples The following example creates an index filter on the orders collection such that for queries that consists
only of an equality match on the status field without any projection and sort, the query optimizer evaluates only the
two specified indexes and the collection scan for the winning plan:
db.runCommand(
{
planCacheSetFilter: "orders",
query: { status: "A" },
262
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
indexes: [
{ cust_id: 1, status: 1 },
{ status: 1, order_date: -1 }
]
}
)
In the query predicate, only the structure of the predicate, including the field names, are significant; the values are
insignificant. As such, the created filter applies to the following operations:
db.orders.find( { status: "D" } )
db.orders.find( { status: "P" } )
See also:
planCacheClearFilters (page 255), planCacheListFilters (page 258)
2.2.2 Database Operations
Authentication Commands
Authentication Commands
Name
authSchemaUpgrade
(page 263)
authenticate
(page 263)
copydbgetnonce
(page 264)
getnonce (page 264)
logout (page 264)
Description
Supports the upgrade process for user data between version 2.4 and 2.6.
Starts an authenticated session using a username and password.
This is an internal command to generate a one-time password for use with the
copydb (page 326) command.
This is an internal command to generate a one-time password for authentication.
Terminates the current authenticated session.
authSchemaUpgrade New in version 2.6.
authSchemaUpgrade
authSchemaUpgrade (page 263) supports the upgrade from 2.4 to 2.6 process for existing systems that
use authentication and authorization. Between 2.4 and 2.6 the schema for user credential documents changed
requiring the authSchemaUpgrade (page 263) process.
See Upgrade User Authorization Data to 2.6 Format (page 764) for more information.
authenticate
authenticate
Clients use authenticate (page 263) to authenticate a connection.
db.auth() (page 100) helper as follows:
When using the shell, use the
db.auth( "username", "password" )
See
db.auth() (page 100) and http://docs.mongodb.org/manual/core/security for more information.
2.2. Database Commands
263
MongoDB Reference Manual, Release 2.8.0-rc3
copydbgetnonce
copydbgetnonce
Client libraries use copydbgetnonce (page 264) to get a one-time password for use with the copydb
(page 326) command.
Note: This command obtains a write lock on the affected database and will block other operations until it has
completed; however, the write lock for this operation is short lived.
getnonce
getnonce
Client libraries use getnonce (page 264) to generate a one-time password for authentication.
logout
logout
The logout (page 264) command terminates the current authenticated session:
{ logout: 1 }
Note: If you’re not logged in and using authentication, logout (page 264) 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 logout (page 264) while using the same database context that you authenticated
to.
If you authenticated to a database such as users or $external, you must issue logout (page 264) against
this database in order to successfully log out.
Example
Use the use <database-name> helper in the interactive mongo (page 610) shell, or the following
db.getSiblingDB() (page 118) in the interactive shell or in mongo (page 610) shell scripts to change
the db object:
db = db.getSiblingDB('<database-name>')
When you have set the database context and db object, you can use the logout (page 264) to log out of
database as in the following operation:
db.runCommand( { logout: 1 } )
User Management Commands
User Management Commands
Name
createUser (page 265)
dropAllUsersFromDatabase (page 266)
dropUser (page 267)
grantRolesToUser (page 267)
revokeRolesFromUser (page 269)
updateUser (page 270)
usersInfo (page 272)
264
Description
Creates a new user.
Deletes all users associated with a database.
Removes a single user.
Grants a role and its privileges to a user.
Removes a role from a user.
Updates a user’s data.
Returns information about the specified users.
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
createUser
Definition
createUser
Creates a new user on the database where you run the command. The createUser (page 265) command
returns a duplicate user error if the user exists. The createUser (page 265) command uses the following
syntax:
{ createUser: "<name>",
pwd: "<cleartext password>",
customData: { <any information> },
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
],
writeConcern: { <write concern> }
}
createUser (page 265) has the following fields:
field string createUser The name of the new user.
field string pwd The user’s password. The pwd field is not required if you run createUser
(page 265) on the $external database to create users who have credentials stored externally
to MongoDB.
any document customData Any arbitrary information. This field can be used to store any data an
admin wishes to associate with this particular user. For example, this could be the user’s full
name or employee id.
field array roles The roles granted to the user. Can specify an empty array [] to create users without
roles.
field boolean digestPassword When true, the mongod (page 583) instance will create the hash
of the user password; otherwise, the client is responsible for creating the hash of the password.
Defaults to true.
field document writeConcern The level of write concern for the creation operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where createUser (page 265) runs, you can either specify
the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
Behavior
Encryption createUser (page 265) sends password to the MongoDB instance in cleartext. To encrypt the password in transit, use SSL.
2.2. Database Commands
265
MongoDB Reference Manual, Release 2.8.0-rc3
External Credentials Users created on the $external database should have credentials stored externally to MongoDB, as, for example, with MongoDB Enterprise installations that use Kerberos.
local Database You cannot create users on the local database.
Required Access You must have the createUser action on a database to create a new user on that database.
You must have the grantRole action on a role’s database to grant the role to another user.
If you have the userAdmin or userAdminAnyDatabase role, you have those actions.
Example The following createUser (page 265) command creates a user accountAdmin01 on the products
database. The command gives accountAdmin01 the clusterAdmin and readAnyDatabase roles on the
admin database and the readWrite role on the products database:
db.getSiblingDB("products").runCommand( { createUser: "accountAdmin01",
pwd: "cleartext password",
customData: { employeeId: 12345 },
roles: [
{ role: "clusterAdmin", db: "admin" },
{ role: "readAnyDatabase", db: "admin" },
"readWrite"
],
writeConcern: { w: "majority" , wtimeout: 5000 }
} )
dropAllUsersFromDatabase
Definition
dropAllUsersFromDatabase
Removes all users from the database on which you run the command.
Warning: The dropAllUsersFromDatabase (page 266) removes all users from the database.
The dropAllUsersFromDatabase (page 266) command has the following syntax:
{ dropAllUsersFromDatabase: 1,
writeConcern: { <write concern> }
}
The dropAllUsersFromDatabase (page 266) document has the following fields:
field integer dropAllUsersFromDatabase Specify 1 to drop all the users from the current database.
field document writeConcern The level of write concern for the removal operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
Required Access You must have the dropUser action on a database to drop a user from that database.
266
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Example The following sequence of operations in the mongo (page 610) shell drops every user from the products
database:
use products
db.runCommand( { dropAllUsersFromDatabase: 1, writeConcern: { w: "majority" } } )
The n field in the results document shows the number of users removed:
{ "n" : 12, "ok" : 1 }
dropUser
Definition
dropUser
Removes the user from the database on which you run the command. The dropUser (page 267) command has
the following syntax:
{
dropUser: "<user>",
writeConcern: { <write concern> }
}
The dropUser (page 267) command document has the following fields:
field string dropUser The name of the user to delete. You must issue the dropUser (page 267)
command while using the database where the user exists.
field document writeConcern The level of write concern for the removal operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
Required Access You must have the dropUser action on a database to drop a user from that database.
Example The following sequence of operations in the mongo (page 610) shell removes accountAdmin01 from
the products database:
use products
db.runCommand( { dropUser: "accountAdmin01",
writeConcern: { w: "majority", wtimeout: 5000 }
} )
grantRolesToUser
Definition
grantRolesToUser
Grants additional roles to a user.
The grantRolesToUser (page 267) command uses the following syntax:
{ grantRolesToUser: "<user>",
roles: [ <roles> ],
writeConcern: { <write concern> }
}
The command has the following fields:
2.2. Database Commands
267
MongoDB Reference Manual, Release 2.8.0-rc3
field string grantRolesToUser The name of the user to give additional roles.
field array roles An array of additional roles to grant to the user.
field document writeConcern The level of write concern for the modification.
The
writeConcern document takes the same fields as the getLastError (page 245) command.
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where grantRolesToUser (page 267) runs, you can either
specify the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
Required Access You must have the grantRole action on a database to grant a role on that database.
Example Given a user accountUser01 in the products database with the following roles:
"roles" : [
{ "role" : "assetsReader",
"db" : "assets"
}
]
The following grantRolesToUser (page 267) operation gives accountUser01 the read role on the stock
database and the readWrite role on the products database.
use products
db.runCommand( { grantRolesToUser: "accountUser01",
roles: [
{ role: "read", db: "stock"},
"readWrite"
],
writeConcern: { w: "majority" , wtimeout: 2000 }
} )
The user accountUser01 in the products database now has the following roles:
"roles" : [
{ "role"
"db" :
},
{ "role"
"db" :
},
{ "role"
"db" :
}
]
: "assetsReader",
"assets"
: "read",
"stock"
: "readWrite",
"products"
revokeRolesFromUser
268
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Definition
revokeRolesFromUser
Removes a one or more roles from a user on the database where the roles exist. The revokeRolesFromUser
(page 269) command uses the following syntax:
{ revokeRolesFromUser: "<user>",
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
],
writeConcern: { <write concern> }
}
The command has the following fields:
field string revokeRolesFromUser The user to remove roles from.
field array roles The roles to remove from the user.
field document writeConcern The level of write concern for the modification.
The
writeConcern document takes the same fields as the getLastError (page 245) command.
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where revokeRolesFromUser (page 269) runs, you can
either specify the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
Required Access You must have the revokeRole action on a database to revoke a role on that database.
Example The accountUser01 user in the products database has the following roles:
"roles" : [
{ "role"
"db" :
},
{ "role"
"db" :
},
{ "role"
"db" :
}
]
: "assetsReader",
"assets"
: "read",
"stock"
: "readWrite",
"products"
The following revokeRolesFromUser (page 269) command removes the two of the user’s roles: the read role
on the stock database and the readWrite role on the products database, which is also the database on which
the command runs:
use products
db.runCommand( { revokeRolesFromUser: "accountUser01",
roles: [
{ role: "read", db: "stock" },
2.2. Database Commands
269
MongoDB Reference Manual, Release 2.8.0-rc3
"readWrite"
],
writeConcern: { w: "majority" }
} )
The user accountUser01 in the products database now has only one remaining role:
"roles" : [
{ "role" : "assetsReader",
"db" : "assets"
}
]
updateUser
Definition
updateUser
Updates the user’s profile on the database on which you run the command. An update to a field completely
replaces the previous field’s values, including updates to the user’s roles array.
Warning: When you update the roles array, you completely replace the previous array’s values. To add
or remove roles without replacing all the user’s existing roles, use the grantRolesToUser (page 267) or
revokeRolesFromUser (page 269) commands.
The updateUser (page 270) command uses the following syntax. To update a user, you must specify the
updateUser field and at least one other field, other than writeConcern:
{ updateUser: "<username>",
pwd: "<cleartext password>",
customData: { <any information> },
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
],
writeConcern: { <write concern> }
}
The command has the following fields:
field string updateUser The name of the user to update.
field string pwd The user’s password.
field document customData Any arbitrary information.
field array roles The roles granted to the user. An update to the roles array overrides the previous
array’s values.
field boolean digestPassword When true, the mongod (page 583) instance will create the hash
of the user password; otherwise, the client is responsible for creating the hash of the password.
Defaults to true.
field document writeConcern The level of write concern for the update operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
In the roles field, you can specify both built-in roles and user-defined role.
270
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
To specify a role that exists in the same database where updateUser (page 270) runs, you can either specify
the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
Behavior updateUser (page 270) sends the password to the MongoDB instance in cleartext. To encrypt the
password in transit, use SSL.
Required Access You must have access that includes the revokeRole action on all databases in order to update a
user’s roles array.
You must have the grantRole action on a role’s database to add a role to a user.
To change another user’s pwd or customData field, you must have the changeAnyPassword and
changeAnyCustomData actions respectively on that user’s database.
To modify your own password and custom data, you must have privileges that grant changeOwnPassword and
changeOwnCustomData actions respectively on the user’s database.
Example Given a user appClient01 in the products database with the following user info:
{
"_id" : "products.appClient01",
"user" : "appClient01",
"db" : "products",
"customData" : { "empID" : "12345", "badge" : "9156" },
"roles" : [
{ "role" : "readWrite",
"db" : "products"
},
{ "role" : "read",
"db" : "inventory"
}
]
}
The following updateUser (page 270) command completely replaces the user’s customData and roles data:
use products
db.runCommand( { updateUser : "appClient01",
customData : { employeeId : "0x3039" },
roles : [
{ role : "read", db : "assets"
]
} )
}
The user appClient01 in the products database now has the following user information:
{
"_id" : "products.appClient01",
"user" : "appClient01",
"db" : "products",
2.2. Database Commands
271
MongoDB Reference Manual, Release 2.8.0-rc3
"customData" : { "employeeId" : "0x3039" },
"roles" : [
{ "role" : "read",
"db" : "assets"
}
]
}
usersInfo
Definition
usersInfo
Returns information about one or more users. To match a single user on the database, use the following form:
{ usersInfo: { user: <name>, db: <db> },
showCredentials: <Boolean>,
showPrivileges: <Boolean>
}
The command has the following fields:
field various usersInfo The user(s) about whom to return information. See Behavior (page 272) for
type and syntax.
field Boolean showCredentials Set the field to true to display the user’s password hash. By default,
this field is false.
field Boolean showPrivileges Set the field to true to show the user’s full set of privileges, including
expanded information for the inherited roles. By default, this field is false. If viewing all
users, you cannot specify this field.
Required Access Users can always view their own information.
To view another user’s information, the user running the command must have privileges that include the viewUser
action on the other user’s database.
Behavior The argument to the usersInfo (page 272) command has multiple forms depending on the requested
information:
Specify a Single User In the usersInfo field, specify a document with the user’s name and database:
{ usersInfo: { user: <name>, db: <db> } }
Alternatively, for a user that exists on the same database where the command runs, you can specify the user by its
name only.
{ usersInfo: <name> }
Specify Multiple Users In the usersInfo field, specify an array of documents:
{ usersInfo: [ { user: <name>, db: <db> },
272
{ user: <name>, db: <db> }, ... ] }
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Specify All Users for a Database In the usersInfo field, specify 1:
{ usersInfo: 1 }
Examples
View Specific Users To see information and privileges, but not the credentials, for the user "Kari" defined in
"home" database, run the following command:
db.runCommand(
{
usersInfo: { user: "Kari", db: "home" },
showPrivileges: true
}
)
To view a user that exists in the current database, you can specify the user by name only. For example, if you are in
the home database and a user named "Kari" exists in the home database, you can run the following command:
db.getSiblingDB("home").runCommand(
{
usersInfo: "Kari",
showPrivileges: true
}
)
View Multiple Users To view info for several users, use an array, with or without the optional fields
showPrivileges and showCredentials. For example:
db.runCommand( { usersInfo: [ { user: "Kari", db: "home" }, { user: "Li", db: "myApp" } ],
showPrivileges: true
} )
View All Users for a Database To view all users on the database the command is run, use a command document
that resembles the following:
db.runCommand( { usersInfo: 1 } )
When viewing all users, you can specify the showCredentials field but not the showPrivileges field.
2.2. Database Commands
273
MongoDB Reference Manual, Release 2.8.0-rc3
Role Management Commands
Role Management Commands
Name
createRole (page 274)
dropAllRolesFromDatabase
(page 275)
dropRole (page 276)
grantPrivilegesToRole
(page 277)
grantRolesToRole (page 278)
invalidateUserCache (page 279)
revokePrivilegesFromRole
(page 279)
revokeRolesFromRole (page 282)
rolesInfo (page 283)
updateRole (page 286)
Description
Creates a role and specifies its privileges.
Deletes all user-defined roles from a database.
Deletes the user-defined role.
Assigns privileges to a user-defined role.
Specifies roles from which a user-defined role inherits privileges.
Flushes the in-memory cache of user information, including
credentials and roles.
Removes the specified privileges from a user-defined role.
Removes specified inherited roles from a user-defined role.
Returns information for the specified role or roles.
Updates a user-defined role.
createRole
Definition
createRole
Creates a role and specifies its privileges. The role applies to the database on which you run the command. The
createRole (page 274) command returns a duplicate role error if the role already exists in the database.
The createRole (page 274) command uses the following syntax:
{ createRole: "<new role>",
privileges: [
{ resource: { <resource> }, actions: [ "<action>", ... ] },
...
],
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
],
writeConcern: <write concern document>
}
The createRole (page 274) command has the following fields:
field string createRole The name of the new role.
field array privileges The privileges to grant the role. A privilege consists of a resource and permitted actions. You must specify the privileges field. Use an empty array to specify no
privileges. For the syntax of a privilege, see the privileges array.
field array roles An array of roles from which this role inherits privileges. You must specify the
roles field. Use an empty array to specify no roles.
field document writeConcern The level of write concern to apply to this operation. The
writeConcern document uses the same fields as the getLastError (page 245) command.
In the roles field, you can specify both built-in roles and user-defined role.
274
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
To specify a role that exists in the same database where createRole (page 274) runs, you can either specify
the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
Behavior A role’s privileges apply to the database where the role is created. The role can inherit privileges from
other roles in its database. A role created on the admin database can include privileges that apply to all databases or
to the cluster and can inherit privileges from roles in other databases.
Required Access To create a role in a database, the user must have:
• the createRole action on that database resource.
• the grantRole action on that database to specify privileges for the new role as well as to specify roles to
inherit from.
Built-in roles userAdmin and userAdminAnyDatabase provide createRole and grantRole actions on
their respective resources.
Example The following createRole (page 274) command creates the myClusterwideAdmin role on the
admin database:
use admin
db.runCommand({ createRole: "myClusterwideAdmin",
privileges: [
{ resource: { cluster: true }, actions: [ "addShard" ] },
{ resource: { db: "config", collection: "" }, actions: [ "find", "update", "insert", "remove" ] }
{ resource: { db: "users", collection: "usersCollection" }, actions: [ "update", "insert", "remov
{ resource: { db: "", collection: "" }, actions: [ "find" ] }
],
roles: [
{ role: "read", db: "admin" }
],
writeConcern: { w: "majority" , wtimeout: 5000 }
})
dropAllRolesFromDatabase
Definition
dropAllRolesFromDatabase
Deletes all user-defined roles on the database where you run the command.
Warning:
database.
The dropAllRolesFromDatabase (page 275) removes all user-defined roles from the
The dropAllRolesFromDatabase (page 275) command takes the following form:
2.2. Database Commands
275
MongoDB Reference Manual, Release 2.8.0-rc3
{
dropAllRolesFromDatabase: 1,
writeConcern: { <write concern> }
}
The command has the following fields:
field integer dropAllRolesFromDatabase Specify 1 to drop all user-defined roles from the
database where the command is run.
field document writeConcern The level of write concern for the removal operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
Required Access You must have the dropRole action on a database to drop a role from that database.
Example The following operations drop all user-defined roles from the products database:
use products
db.runCommand(
{
dropAllRolesFromDatabase: 1,
writeConcern: { w: "majority" }
}
)
The n field in the results document reports the number of roles dropped:
{ "n" : 4, "ok" : 1 }
dropRole
Definition
dropRole
Deletes a user-defined role from the database on which you run the command.
The dropRole (page 276) command uses the following syntax:
{
dropRole: "<role>",
writeConcern: { <write concern> }
}
The dropRole (page 276) command has the following fields:
field string dropRole The name of the user-defined role to remove from the database.
field document writeConcern The level of write concern for the removal operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
Required Access You must have the dropRole action on a database to drop a role from that database.
276
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Example The following operations remove the readPrices role from the products database:
use products
db.runCommand(
{
dropRole: "readPrices",
writeConcern: { w: "majority" }
}
)
grantPrivilegesToRole
Definition
grantPrivilegesToRole
Assigns additional privileges to a user-defined role defined on the database on which the command is run. The
grantPrivilegesToRole (page 277) command uses the following syntax:
{
grantPrivilegesToRole: "<role>",
privileges: [
{
resource: { <resource> }, actions: [ "<action>", ... ]
},
...
],
writeConcern: { <write concern> }
}
The grantPrivilegesToRole (page 277) command has the following fields:
field string grantPrivilegesToRole The name of the user-defined role to grant privileges to.
field array privileges The privileges to add to the role.
privileges.
For the format of a privilege, see
field document writeConcern The level of write concern for the modification.
The
writeConcern document takes the same fields as the getLastError (page 245) command.
Behavior A role’s privileges apply to the database where the role is created. A role created on the admin database
can include privileges that apply to all databases or to the cluster.
Required Access You must have the grantRole action on the database a privilege targets in order to grant the
privilege. To grant a privilege on multiple databases or on the cluster resource, you must have the grantRole
action on the admin database.
Example The following grantPrivilegesToRole (page 277) command grants two additional privileges to the
service role that exists in the products database:
use products
db.runCommand(
{
grantPrivilegesToRole: "service",
privileges: [
{
2.2. Database Commands
277
MongoDB Reference Manual, Release 2.8.0-rc3
resource: { db: "products", collection: "" }, actions: [ "find" ]
},
{
resource: { db: "products", collection: "system.indexes" }, actions: [ "find" ]
}
],
writeConcern: { w: "majority" , wtimeout: 5000 }
}
)
The first privilege in the privileges array allows the user to search on all non-system collections in the products
database. The privilege does not allow searches on system collections (page 688), such as the system.indexes
(page 689) collection. To grant access to these system collections, explicitly provision access in the privileges
array. See http://docs.mongodb.org/manual/reference/resource-document.
The second privilege explicitly allows the find action on system.indexes (page 689) collections on all
databases.
grantRolesToRole
Definition
grantRolesToRole
Grants roles to a user-defined role.
The grantRolesToRole (page 278) command affects roles on the database where the command runs.
grantRolesToRole (page 278) has the following syntax:
{ grantRolesToRole: "<role>",
roles: [
{ role: "<role>", db: "<database>" },
...
],
writeConcern: { <write concern> }
}
The grantRolesToRole (page 278) command has the following fields:
field string grantRolesToRole The name of a role to add subsidiary roles.
field array roles An array of roles from which to inherit.
field document writeConcern The level of write concern for the modification.
The
writeConcern document takes the same fields as the getLastError (page 245) command.
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where grantRolesToRole (page 278) runs, you can either
specify the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
278
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Behavior A role can inherit privileges from other roles in its database. A role created on the admin database can
inherit privileges from roles in any database.
Required Access You must have the grantRole action on a database to grant a role on that database.
Example The following grantRolesToRole (page 278) command updates the productsReaderWriter
role in the products database to inherit the privileges of the productsReader role in the products database:
use products
db.runCommand(
{ grantRolesToRole: "productsReaderWriter",
roles: [
"productsReader"
],
writeConcern: { w: "majority" , wtimeout: 5000 }
}
)
invalidateUserCache
Definition
invalidateUserCache
New in version 2.6.
Flushes user information from in-memory cache, including removal of each user’s credentials and
roles. This allows you to purge the cache at any given moment, regardless of the interval set in the
userCacheInvalidationIntervalSecs parameter.
invalidateUserCache (page 279) has the following syntax:
db.runCommand( { invalidateUserCache: 1 } )
Required Access You must have privileges that include the invalidateUserCache action on the cluster resource in order to use this command.
revokePrivilegesFromRole
Definition
revokePrivilegesFromRole
Removes the specified privileges from the user-defined role on the database where the command is run. The
revokePrivilegesFromRole (page 279) command has the following syntax:
{
revokePrivilegesFromRole: "<role>",
privileges:
[
{ resource: { <resource> }, actions: [ "<action>", ... ] },
...
],
writeConcern: <write concern document>
}
The revokePrivilegesFromRole (page 279) command has the following fields:
2.2. Database Commands
279
MongoDB Reference Manual, Release 2.8.0-rc3
field string revokePrivilegesFromRole The user-defined role to revoke privileges from.
field array privileges An array of privileges to remove from the role. See privileges for more
information on the format of the privileges.
field document writeConcern The level of write concern for the modification.
The
writeConcern document takes the same fields as the getLastError (page 245) command.
Behavior To revoke a privilege, the resource document pattern must match exactly the resource field of
that privilege. The actions field can be a subset or match exactly.
For example, consider the role accountRole in the products database with the following privilege that specifies
the products database as the resource:
{
"resource" : {
"db" : "products",
"collection" : ""
},
"actions" : [
"find",
"update"
]
}
You cannot revoke find and/or update from just one collection in the products database. The following operations result in no change to the role:
use products
db.runCommand(
{
revokePrivilegesFromRole: "accountRole",
privileges:
[
{
resource : {
db : "products",
collection : "gadgets"
},
actions : [
"find",
"update"
]
}
]
}
)
db.runCommand(
{
revokePrivilegesFromRole: "accountRole",
privileges:
[
{
resource : {
db : "products",
collection : "gadgets"
},
280
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
actions : [
"find"
]
}
]
}
)
To revoke the "find" and/or the "update" action from the role accountRole, you must match the resource
document exactly. For example, the following operation revokes just the "find" action from the existing privilege.
use products
db.runCommand(
{
revokePrivilegesFromRole: "accountRole",
privileges:
[
{
resource : {
db : "products",
collection : ""
},
actions : [
"find"
]
}
]
}
)
Required Access You must have the revokeRole action on the database a privilege targets in order to revoke
that privilege. If the privilege targets multiple databases or the cluster resource, you must have the revokeRole
action on the admin database.
Example The following operation removes multiple privileges from the associates role in the products
database:
use products
db.runCommand(
{
revokePrivilegesFromRole: "associate",
privileges:
[
{
resource: { db: "products", collection: "" },
actions: [ "createCollection", "createIndex", "find" ]
},
{
resource: { db: "products", collection: "orders" },
actions: [ "insert" ]
}
],
writeConcern: { w: "majority" }
}
)
2.2. Database Commands
281
MongoDB Reference Manual, Release 2.8.0-rc3
revokeRolesFromRole
Definition
revokeRolesFromRole
Removes the specified inherited roles from a role. The revokeRolesFromRole (page 282) command has
the following syntax:
{ revokeRolesFromRole: "<role>",
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
],
writeConcern: { <write concern> }
}
The command has the following fields:
field string revokeRolesFromRole The role from which to remove inherited roles.
field array roles The inherited roles to remove.
field document writeConcern The level of write concern to apply to this operation. The
writeConcern document uses the same fields as the getLastError (page 245) command.
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where revokeRolesFromRole (page 282) runs, you can
either specify the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
Required Access You must have the revokeRole action on a database to revoke a role on that database.
Example The purchaseAgents role in the emea database inherits privileges from several other roles, as listed
in the roles array:
{
"_id" : "emea.purchaseAgents",
"role" : "purchaseAgents",
"db" : "emea",
"privileges" : [],
"roles" : [
{
"role" : "readOrdersCollection",
"db" : "emea"
},
{
"role" : "readAccountsCollection",
"db" : "emea"
},
{
"role" : "writeOrdersCollection",
282
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
"db" : "emea"
}
]
}
The following revokeRolesFromRole (page 282) operation on the emea database removes two roles from the
purchaseAgents role:
use emea
db.runCommand( { revokeRolesFromRole: "purchaseAgents",
roles: [
"writeOrdersCollection",
"readOrdersCollection"
],
writeConcern: { w: "majority" , wtimeout: 5000 }
} )
The purchaseAgents role now contains just one role:
{
"_id" : "emea.purchaseAgents",
"role" : "purchaseAgents",
"db" : "emea",
"privileges" : [],
"roles" : [
{
"role" : "readAccountsCollection",
"db" : "emea"
}
]
}
rolesInfo
Definition
rolesInfo
Returns inheritance and privilege information for specified roles, including both user-defined roles and built-in
roles.
The rolesInfo (page 283) command can also retrieve all roles scoped to a database.
The command has the following fields:
field string,document,array,integer rolesInfo The role(s) to return information about. For the syntax for specifying roles, see Behavior (page 283).
field Boolean showPrivileges Set the field to true to show role privileges, including both privileges inherited from other roles and privileges defined directly. By default, the command returns
only the roles from which this role inherits privileges and does not return specific privileges.
field Boolean showBuiltinRoles When the rolesInfo field is set to 1,
set
showBuiltinRoles to true to include built-in roles in the output. By default this
field is set to false, and the output for rolesInfo: 1 displays only user-defined roles.
Behavior
2.2. Database Commands
283
MongoDB Reference Manual, Release 2.8.0-rc3
Return Information for a Single Role To specify a role from the current database, specify the role by its name:
{ rolesInfo: "<rolename>" }
To specify a role from another database, specify the role by a document that specifies the role and database:
{ rolesInfo: { role: "<rolename>", db: "<database>" } }
Return Information for Multiple Roles To specify multiple roles, use an array. Specify each role in the array as a
document or string. Use a string only if the role exists on the database on which the command runs:
{
rolesInfo: [
"<rolename>",
{ role: "<rolename>", db: "<database>" },
...
]
}
Return Information for All Roles in the Database To specify all roles in the database on which the command
runs, specify rolesInfo: 1. By default MongoDB displays all the user-defined roles in the database. To include
built-in roles as well, include the parameter-value pair showBuiltinRoles: true:
{ rolesInfo: 1, showBuiltinRoles: true }
Required Access To view a role’s information, you must be explicitly granted the role or must have the viewRole
action on the role’s database.
Output
rolesInfo.role
The name of the role.
rolesInfo.db
The database on which the role is defined. Every database has built-in roles. A database might also have
user-defined roles.
rolesInfo.isBuiltin
A value of true indicates the role is a built-in role. A value of false indicates the role is a user-defined role.
rolesInfo.roles
The roles that directly provide privileges to this role and the databases on which the roles are defined.
rolesInfo.inheritedRoles
All roles from which this role inherits privileges. This includes the roles in the rolesInfo.roles (page 284)
array as well as the roles from which the roles in the rolesInfo.roles (page 284) array inherit privileges.
All privileges apply to the current role. The documents in this field list the roles and the databases on which
they are defined.
rolesInfo.privileges
The privileges directly specified by this role; i.e. the array excludes privileges inherited from other roles.
By default the output does not include the privileges (page 284) field. To include the field, specify
showPrivileges: true when running the rolesInfo (page 283) command.
Each privilege document specifies the resources and the actions allowed on the resources.
284
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
rolesInfo.inheritedPrivileges
All privileges granted by this role, including those inherited from other roles. By default the output does not
include the inheritedPrivileges (page 284) field. To include the field, specify showPrivileges:
true when running the rolesInfo (page 283) command.
Each privilege document specifies the resources and the actions allowed on the resources.
Examples
View Information for a Single Role The following command returns the role inheritance information for the role
associate defined in the products database:
db.runCommand(
{
rolesInfo: { role: "associate", db: "products" }
}
)
The following command returns the role inheritance information for the role siteManager on the database on which
the command runs:
db.runCommand(
{
rolesInfo: "siteManager"
}
)
The following command returns both the role inheritance and the privileges for the role associate defined on the
products database:
db.runCommand(
{
rolesInfo: { role: "associate", db: "products" },
showPrivileges: true
}
)
View Information for Several Roles The following command returns information for two roles on two different
databases:
db.runCommand(
{
rolesInfo: [
{ role: "associate", db: "products" },
{ role: "manager", db: "resources" }
]
}
)
The following returns both the role inheritance and the privileges:
db.runCommand(
{
rolesInfo: [
{ role: "associate", db: "products" },
{ role: "manager", db: "resources" }
],
2.2. Database Commands
285
MongoDB Reference Manual, Release 2.8.0-rc3
showPrivileges: true
}
)
View All User-Defined Roles for a Database The following operation returns all user-defined roles on the database
on which the command runs and includes privileges:
db.runCommand(
{
rolesInfo: 1,
showPrivileges: true
}
)
View All User-Defined and Built-In Roles for a Database The following operation returns all roles on the database
on which the command runs, including both built-in and user-defined roles:
db.runCommand(
{
rolesInfo: 1,
showBuiltinRoles: true
}
)
updateRole
Definition
updateRole
Updates a user-defined role. The updateRole (page 286) command must run on the role’s database.
An update to a field completely replaces the previous field’s values. To grant or remove roles or privileges
without replacing all values, use one or more of the following commands:
•grantRolesToRole (page 278)
•grantPrivilegesToRole (page 277)
•revokeRolesFromRole (page 282)
•revokePrivilegesFromRole (page 279)
Warning: An update to the privileges or roles array completely replaces the previous array’s values.
The updateRole (page 286) command uses the following syntax. To update a role, you must provide the
privileges array, roles array, or both:
{
updateRole: "<role>",
privileges:
[
{ resource: { <resource> }, actions: [ "<action>", ... ] },
...
],
roles:
[
286
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
{ role: "<role>", db: "<database>" } | "<role>",
...
],
writeConcern: <write concern document>
}
The updateRole (page 286) command has the following fields:
field string updateRole The name of the user-defined role role to update.
field array privileges Required if you do not specify roles array. The privileges to grant the role.
An update to the privileges array overrides the previous array’s values. For the syntax for
specifying a privilege, see the privileges array.
field array roles Required if you do not specify privileges array. The roles from which this
role inherits privileges. An update to the roles array overrides the previous array’s values.
field document writeConcern The level of write concern for the update operation. The
writeConcern document takes the same fields as the getLastError (page 245) command.
In the roles field, you can specify both built-in roles and user-defined role.
To specify a role that exists in the same database where updateRole (page 286) runs, you can either specify
the role with the name of the role:
"readWrite"
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" }
To specify a role that exists in a different database, specify the role with a document.
Behavior A role’s privileges apply to the database where the role is created. The role can inherit privileges from
other roles in its database. A role created on the admin database can include privileges that apply to all databases or
to the cluster and can inherit privileges from roles in other databases.
Required Access You must have the revokeRole action on all databases in order to update a role.
You must have the grantRole action on the database of each role in the roles array to update the array.
You must have the grantRole action on the database of each privilege in the privileges array to update the
array. If a privilege’s resource spans databases, you must have grantRole on the admin database. A privilege
spans databases if the privilege is any of the following:
• a collection in all databases
• all collections and all database
• the cluster resource
Example The following is an example of the updateRole (page 286) command that updates the
myClusterwideAdmin role on the admin database. While the privileges and the roles arrays are both
optional, at least one of the two is required:
use admin
db.runCommand(
{
2.2. Database Commands
287
MongoDB Reference Manual, Release 2.8.0-rc3
updateRole: "myClusterwideAdmin",
privileges:
[
{
resource: { db: "", collection: "" },
actions: [ "find" , "update", "insert", "remove" ]
}
],
roles:
[
{ role: "dbAdminAnyDatabase", db: "admin" }
],
writeConcern: { w: "majority" }
}
)
To view a role’s privileges, use the rolesInfo (page 283) command.
Replication Commands
Replication Commands
Name
applyOps (page 288)
isMaster (page 289)
replSetFreeze (page 291)
replSetGetConfig
(page 292)
replSetGetStatus
(page 296)
replSetInitiate
(page 299)
replSetMaintenance
(page 300)
replSetReconfig
(page 300)
replSetStepDown
(page 301)
replSetSyncFrom
(page 302)
resync (page 302)
Description
Internal command that applies oplog entries to the current data set.
Displays information about this member’s role in the replica set, including
whether it is the master.
Prevents the current member from seeking election as primary for a period of
time.
Returns the replica set’s configuration object.
Returns a document that reports on the status of the replica set.
Initializes a new replica set.
Enables or disables a maintenance mode, which puts a secondary node in a
RECOVERING state.
Applies a new configuration to an existing replica set.
Forces the current primary to step down and become a secondary, forcing an
election.
Explicitly override the default logic for selecting a member to replicate from.
Forces a mongod (page 583) to re-synchronize from the master. For
master-slave replication only.
applyOps
Definition
applyOps
Applies specified oplog entries to a mongod (page 583) instance. The applyOps (page 288) command is
primarily an internal command.
288
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
If authorization is enabled, you must have access to all actions on all resources in order to run applyOps
(page 288). Providing such access is not recommended, but if your organization requires a user to run
applyOps (page 288), create a role that grants anyAction on resource-anyresource. Do not assign this
role to any other user.
The applyOps (page 288) command has the following prototype form:
db.runCommand( { applyOps: [ <operations> ],
preCondition: [ { ns: <namespace>, q: <query>, res: <result> } ] } )
The applyOps (page 288) command takes a document with the following fields:
field array applyOps The oplog entries to apply.
field array preCondition An array of documents that contain the conditions that must be true in
order to apply the oplog entry. Each document contains a set of conditions, as described in the
next table.
field array alwaysUpsert A flag that indicates whether to apply update operations in the oplog as
ref:upserts <write-operations-upsert-behavior>. When true, all updates become upserts to
prevent failures as a results of sequences of updates followed by deletes: this is the same mode of
operation as normal replication in secondaries. When false, updates are applied unmodified:
this is the same mode of operation used during initial sync operations. true by default.
The preCondition array takes one or more documents with the following fields:
field string ns A namespace. If you use this field, applyOps (page 288) applies oplog entries only
for the collection described by this namespace.
param string q Specifies the query that produces the results specified in the res field.
param string res The results of the query in the q field that must match to apply the oplog entry.
Behavior
Warning: This command obtains a global write lock and will block other operations until it has completed.
isMaster
Definition
isMaster
isMaster (page 289) returns a document that describes the role of the mongod (page 583) instance.
If the instance is a member of a replica set, then isMaster (page 289) returns a subset of the replica set
configuration and status including whether or not the instance is the primary of the replica set.
When sent to a mongod (page 583) instance that is not a member of a replica set, isMaster (page 289) returns
a subset of this information.
MongoDB drivers and clients use isMaster (page 289) to determine the state of the replica set members and
to discover additional members of a replica set.
The db.isMaster() (page 119) method in the mongo (page 610) shell provides a wrapper around
isMaster (page 289).
The command takes the following form:
{ isMaster: 1 }
See also:
db.isMaster() (page 119)
2.2. Database Commands
289
MongoDB Reference Manual, Release 2.8.0-rc3
Output
All Instances The following isMaster (page 289) fields are common across all roles:
isMaster.ismaster
A boolean value that reports when this node is writable. If true, then this instance is a primary in a replica
set, or a master in a master-slave configuration, or a mongos (page 601) instance, or a standalone mongod
(page 583).
This field will be false if the instance is a secondary member of a replica set or if the member is an arbiter of
a replica set.
isMaster.rbid
New in version 2.8.
An ObjectId value that changes any time that a rollback may have occurred. For internal use.
isMaster.maxBsonObjectSize
The maximum permitted size of a BSON object in bytes for this mongod (page 583) process. If not provided,
clients should assume a max size of “16 * 1024 * 1024”.
isMaster.maxMessageSizeBytes
New in version 2.4.
The maximum permitted size of a BSON wire protocol message. The default value is 48000000 bytes.
isMaster.localTime
New in version 2.2.
Returns the local server time in UTC. This value is an ISO date.
isMaster.minWireVersion
New in version 2.6.
The earliest version of the wire protocol that this mongod (page 583) or mongos (page 601) instance is capable
of using to communicate with clients.
Clients may use minWireVersion (page 290) to help negotiate compatibility with MongoDB.
isMaster.maxWireVersion
New in version 2.6.
The latest version of the wire protocol that this mongod (page 583) or mongos (page 601) instance is capable
of using to communicate with clients.
Clients may use maxWireVersion (page 290) to help negotiate compatibility with MongoDB.
Sharded Instances mongos (page 601) instances add the following field to the isMaster (page 289) response
document:
isMaster.msg
Contains the value isdbgrid when isMaster (page 289) returns from a mongos (page 601) instance.
Replica Sets isMaster (page 289) contains these fields when returned by a member of a replica set:
isMaster.setName
The name of the current :replica set.
isMaster.secondary
A boolean value that, when true, indicates if the mongod (page 583) is a secondary member of a replica set.
290
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
isMaster.hosts
An array of strings in the format of "[hostname]:[port]" that lists all members of the replica set that are
neither hidden, passive, nor arbiters.
Drivers use this array and the isMaster.passives (page 291) to determine which members to read from.
isMaster.passives
An array of strings in the format of "[hostname]:[port]" listing all members of the replica set which
have a priority of 0.
This field only appears if there is at least one member with a priority of 0.
Drivers use this array and the isMaster.hosts (page 290) to determine which members to read from.
isMaster.arbiters
An array of strings in the format of "[hostname]:[port]" listing all members of the replica set that are
arbiters.
This field only appears if there is at least one arbiter in the replica set.
isMaster.primary
A string in the format of "[hostname]:[port]" listing the current primary member of the replica set.
isMaster.arbiterOnly
A boolean value that , when true, indicates that the current instance is an arbiter. The arbiterOnly
(page 291) field is only present, if the instance is an arbiter.
isMaster.passive
A boolean value that, when true, indicates that the current instance is passive. The passive (page 291) field
is only present for members with a priority of 0.
isMaster.hidden
A boolean value that, when true, indicates that the current instance is hidden. The hidden (page 291) field
is only present for hidden members.
isMaster.tags
A
document
that
lists
any
tags
assigned
to
this
member.
This
field
is
only
present
if
there
are
tags
assigned
to
the
member.
See
http://docs.mongodb.org/manual/tutorial/configure-replica-set-tag-sets
for more information.
isMaster.me
The [hostname]:[port] of the member that returned isMaster (page 289).
isMaster.electionId
New in version 2.8.0.
A unique identifier for each election. Included only in the output of isMaster (page 289) for the primary.
Used by clients to determine when elections occur.
replSetFreeze
replSetFreeze
The replSetFreeze (page 291) command prevents a replica set member from seeking election for the specified number of seconds. Use this command in conjunction with the replSetStepDown (page 301) command
to make a different node in the replica set a primary.
The replSetFreeze (page 291) command uses the following syntax:
{ replSetFreeze: <seconds> }
2.2. Database Commands
291
MongoDB Reference Manual, Release 2.8.0-rc3
If you want to unfreeze a replica set member before the specified number of seconds has elapsed, you can issue
the command with a seconds value of 0:
{ replSetFreeze: 0 }
Restarting the mongod (page 583) process also unfreezes a replica set member.
replSetFreeze (page 291) is an administrative command, and you must issue it against the admin database.
replSetGetConfig New in version 2.8.0.
Definition
replSetGetConfig
Returns a document that describes the current configuration of the replica set. Invoke the directly, using the
following operation:
db.runCommand( { replSetGetConfig: 1 } );
Access the data provided by replSetGetConfig (page 292) using rs.conf() (page 174) in the mongo
(page 610) shell, as in the following:
rs.conf();
Output
replSetGetConfig._id
Type: string
The name of the replica set. Once set, you cannot change the name of a replica set.
See
replSetName or --replSet (page 594) for information on setting the replica set name.
replSetGetConfig.version
An incrementing number used to distinguish revisions of the replica set configuration object from previous
iterations of the configuration.
members
replSetGetConfig.members
Type: array
An array of member configuration documents, one for each member of the replica set. The members (page 292)
array is a zero-indexed array.
Each member-specific configuration document can contain the following fields:
replSetGetConfig.members[n]._id
Type: integer
A numeric identifier of every member in the replica set. Once set, you cannot change the _id (page 292)
of a member.
Note: When updating the replica configuration object, access the replica set members in the members
array with the array index. The array index begins with 0. Do not confuse this index value with the value
of the _id field in each document in the members array.
292
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
replSetGetConfig.members[n].host
Type: string
The hostname and, if specified, the port number, of the set member.
The hostname name must be resolvable for every host in the replica set.
Warning: host (page 292) cannot hold a value that resolves to localhost or the local interface
unless all members of the set are on hosts that resolve to localhost.
replSetGetConfig.members[n].arbiterOnly
Optional.
Type: boolean
Default: false
A boolean that identifies an arbiter. A value of true indicates that the member is an arbiter.
When using the rs.addArb() (page 174) method to add an arbiter, the method automatically sets
arbiterOnly (page 293) to true for the added member.
replSetGetConfig.members[n].buildIndexes
Optional.
Type: boolean
Default: true
A boolean that indicates whether the mongod (page 583) builds indexes on this member. You can only
set this value when adding a member to a replica set. You cannot change buildIndexes (page 293)
field after the member has been added to the set. To add a member, see rs.add() (page 173) and
rs.reconfig() (page 176).
Do not set to false for mongod (page 583) instances that receive queries from clients.
Setting buildIndexes to false may be useful if all the following conditions are true:
•you are only using this instance to perform backups using mongodump (page 622), and
•this member will receive no queries, and
•index creation and maintenance overburdens the host system.
Even if set to false, secondaries will build indexes on the _id field in order to facilitate operations
required for replication.
Warning:
If you set buildIndexes (page 293) to false, you must also set priority
(page 294) to 0. If priority (page 294) is not 0, MongoDB will return an error when attempting to add a member with buildIndexes (page 293) equal to false.
To ensure the member receives no queries, you should make all instances that do not build indexes
hidden.
Other secondaries cannot replicate from a member where buildIndexes (page 293) is false.
replSetGetConfig.members[n].hidden
Optional.
Type: boolean
Default: false
2.2. Database Commands
293
MongoDB Reference Manual, Release 2.8.0-rc3
When this value is true, the replica set hides this instance and does not include the member in the output
of db.isMaster() (page 119) or isMaster (page 289). This prevents read operations (i.e. queries)
from ever reaching this host by way of secondary read preference.
See also:
Hidden Replica Set Members
replSetGetConfig.members[n].priority
Optional.
Type: Number, between 0 and 1000.
Default: 1.0
A number that indicates the relative eligibility of a member to become a primary.
Specify higher values to make a member more eligible to become primary, and lower values to make the
member less eligible. Priorities are only used in comparison to each other. Members of the set will veto
election requests from members when another eligible member has a higher priority value. Changing the
balance of priority in a replica set will trigger an election.
A priority (page 294) of 0 makes it impossible for a member to become primary.
See also:
Replica Set Elections.
replSetGetConfig.members[n].tags
Optional.
Type: document
Default: none
A document that contains arbitrary field and value pairs for describing or tagging members in order to extend write concern and read preference and thereby allowing configurable data center awareness.
Use tags to configure write concerns in conjunction with getLastErrorModes (page 295) and
getLastErrorDefaults (page 295).
Important: In tag sets, all tag values must be strings.
For more information on configuring tag sets for read preference and write concern, see
http://docs.mongodb.org/manual/tutorial/configure-replica-set-tag-sets.
replSetGetConfig.members[n].slaveDelay
Optional.
Type: integer
Default: 0
The number of seconds “behind” the primary that this replica set member should “lag”.
Use this option to create delayed members. Delayed members maintain a copy of the data that reflects the
state of the data at some time in the past.
See also:
http://docs.mongodb.org/manual/core/replica-set-delayed-member
replSetGetConfig.members[n].votes
Optional.
294
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Type: integer
Default: 1
The number of votes a server will cast in a replica set election. The number of votes each member has is
either 1 or 0, and arbiters always have exactly 1 vote.
A replica set can have up to 12 members, but can have at most only 7 voting members. If you need more
than 7 members in one replica set, set votes (page 294) to 0 for the additional non-voting members.
Note: Deprecated since version 2.6: votes values greater than 1.
Earlier versions of MongoDB allowed a member to have more than 1 vote by setting votes to a value
greater than 1. Setting votes to value greater than 1 now produces a warning message.
settings
replSetGetConfig.settings
Optional.
Type: document
A document that contains configuration options that apply to the whole replica set.
The settings (page 295) document contain the following fields:
replSetGetConfig.settings.chainingAllowed
New in version 2.2.4.
Optional.
Type: boolean
Default: true
When chainingAllowed (page 295) is true, the replica set allows secondary members to replicate
from other secondary members. When chainingAllowed (page 295) is false, secondaries can replicate only from the primary.
When you run rs.conf() (page 174) to view a replica set’s configuration, the chainingAllowed
(page 295) field appears only when set to false. If not set, chainingAllowed (page 295) is true.
See also:
http://docs.mongodb.org/manual/tutorial/manage-chained-replication
replSetGetConfig.settings.getLastErrorDefaults
Optional.
Type: document
A document that specifies the write concern for the replica set. The replica set will use this write
concern only when write operations (page 751) or getLastError (page 245) specify no other write
concern.
If getLastErrorDefaults (page 295) is not set, the default write concern for the replica set only
requires confirmation from the primary.
replSetGetConfig.settings.getLastErrorModes
Optional.
Type: document
A document used to define an extended write concern through the use of tags (page 294). The extended
write concern can provide data-center awareness.
2.2. Database Commands
295
MongoDB Reference Manual, Release 2.8.0-rc3
For example, the following document defines an extended write concern named eastCoast and associates with a write to a member that has the east tag.
{ getLastErrorModes: { eastCoast: { "east": 1 } } }
Write operations to the replica set can use the extended write concern, e.g. { w:
"eastCoast" }.
See http://docs.mongodb.org/manual/tutorial/configure-replica-set-tag-sets
for more information and example.
replSetGetConfig.settings.heartbeatTimeoutSecs
Optional.
Type: int
Default: 10
Number of seconds that the replica set members wait for a successful heartbeat from each other. If a
member does not respond in time, other members mark the delinquent member as inaccessible.
replSetGetStatus
Definition
replSetGetStatus
The replSetGetStatus command returns the status of the replica set from the point of view of the current
server. You must run the command against the admin database. The command has the following prototype
format:
{ replSetGetStatus: 1 }
The value specified does not affect the output of the command. Data provided by this command derives from
data included in heartbeats sent to the current instance by other members of the replica set. Because of the
frequency of heartbeats, these data can be several seconds out of date.
You can also access this functionality through the rs.status() (page 179) helper in the mongo (page 610)
shell.
The mongod (page 583) must have replication enabled and be a member of a replica set for the for
replSetGetStatus (page 296) to return successfully.
Example The following example runs the replSetGetStatus command on the admin database of the replica set
primary:
use admin
db.runCommand( { replSetGetStatus : 1 } )
Consider the following example output:
{
"set" : "replset",
"date" : ISODate("2014-05-01T14:44:03Z"),
"myState" : 1,
"members" : [
{
"_id" : 0,
"name" : "m1.example.net:27017",
"health" : 1,
"state" : 1,
296
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
"stateStr" : "PRIMARY",
"uptime" : 269,
"optime" : Timestamp(1404225575, 11),
"optimeDate" : ISODate("2014-05-01T14:39:35Z"),
"electionTime" : Timestamp(1404225586, 1),
"electionDate" : ISODate("2014-05-01T14:39:46Z"),
"self" : true
},
{
"_id" : 1,
"name" : "m2.example.net:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 265,
"optime" : Timestamp(1404225575, 11),
"optimeDate" : ISODate("2014-05-01T14:39:35Z"),
"lastHeartbeat" : ISODate("2014-05-01T14:44:03Z"),
"lastHeartbeatRecv" : ISODate("2014-05-01T14:44:02Z"),
"pingMs" : 0,
"syncingTo" : "m1.example.net:27017"
},
{
"_id" : 2,
"name" : "m3.example.net:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 265,
"optime" : Timestamp(1404225575, 11),
"optimeDate" : ISODate("2014-05-01T14:39:35Z"),
"lastHeartbeat" : ISODate("2014-05-01T14:44:02Z"),
"lastHeartbeatRecv" : ISODate("2014-05-01T14:44:02Z"),
"pingMs" : 0,
"syncingTo" : "m1.example.net:27017"
}
],
"ok" : 1
}
Output The replSetGetStatus command returns a document with the following fields:
replSetGetStatus.set
The set value is the name of the replica set, configured in the replSetName setting. This is the same value
as _id in rs.conf() (page 174).
replSetGetStatus.date
The value of the date field is an ISODate of the current time, according to the current server. Compare this to
the value of the lastHeartbeat (page ??) to find the operational lag between the current host and the other
hosts in the set.
replSetGetStatus.myState
The value of myState (page 297) is an integer between 0 and 10 that represents the replica state of the
current member.
replSetGetStatus.members
The members field holds an array that contains a document for every member in the replica set.
2.2. Database Commands
297
MongoDB Reference Manual, Release 2.8.0-rc3
replSetGetStatus.members[n].name
The name field holds the name of the server.
replSetGetStatus.members[n].self
The self field is only included in the document for the current mongod instance in the members array.
It’s value is true.
replSetGetStatus.members[n].health
The health value is only present for the other members of the replica set (i.e. not the member that returns
rs.status (page 179).) This field conveys if the member is up (i.e. 1) or down (i.e. 0.)
replSetGetStatus.members.state
The value of state is an integer between 0 and 10 that represents the replica state of the member.
replSetGetStatus.members[n].stateStr
A string that describes state.
replSetGetStatus.members[n].uptime
The uptime (page 298) field holds a value that reflects the number of seconds that this member has been
online.
This value does not appear for the member that returns the rs.status() (page 179) data.
replSetGetStatus.members[n].optime
Information regarding the last operation from the operation log that this member has applied.
replSetGetStatus.members[n].optime.t
A 32-bit timestamp of the last operation applied to this member of the replica set from the oplog.
replSetGetStatus.members[n].optime.i
An incremented field, which reflects the number of operations in since the last time stamp. This value
only increases if there is more than one operation per second.
replSetGetStatus.members[n].optimeDate
An ISODate formatted date string that reflects the last entry from the oplog that this member applied. If this
differs significantly from lastHeartbeat (page 298) this member is either experiencing “replication
lag” or there have not been any new operations since the last update. Compare members.optimeDate
between all of the members of the set.
replSetGetStatus.members[n].electionTime
For the current primary, information regarding the election time from the operation log. See
http://docs.mongodb.org/manual/core/replica-set-elections for more information about elections.
replSetGetStatus.members[n].electionTime.t
For the current primary, a 32-bit timestamp of the election time applied to this member of the replica
set from the oplog.
replSetGetStatus.members[n].electionTime.i
For the current primary, an incremented field which reflects the number of operations in since the last
time stamp. This value only increases if there is more than one operation per second.
replSetGetStatus.members[n].electionDate
For the current primary, an ISODate formatted date string that reflects the election date. See
http://docs.mongodb.org/manual/core/replica-set-elections for more information about elections.
replSetGetStatus.members[n].self
Indicates which replica set member processed the replSetGetStatus command.
replSetGetStatus.members[n].lastHeartbeat
The lastHeartbeat value provides an ISODate formatted date and time of the transmission time of
298
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
last heartbeat received from this member. Compare this value to the value of the date (page 297) and
lastHeartBeatRecv field to track latency between these members.
This value does not appear for the member that returns the rs.status() (page 179) data.
replSetGetStatus.members[n].lastHeartbeatRecv
The lastHeartbeatRecv value provides an ISODate formatted date and time that the last heartbeat was received from this member. Compare this value to the value of the date (page 297) and
lastHeartBeat field to track latency between these members.
replSetGetStatus.members[n].lastHeartbeatMessage
When the last heartbeat included an extra message, the lastHeartbeatMessage (page 299) contains
a string representation of that message.
replSetGetStatus.members[n].pingMs
The pingMs represents the number of milliseconds (ms) that a round-trip packet takes to travel between
the remote member and the local instance.
This value does not appear for the member that returns the rs.status() (page 179) data.
replSetGetStatus.members[n].syncingTo
The syncingTo field is only present on the output of rs.status() (page 179) on secondary and
recovering members, and holds the hostname of the member from which this instance is syncing.
replSetInitiate
replSetInitiate
The replSetInitiate (page 299) command initializes a new replica set. Use the following syntax:
{ replSetInitiate : <config_document> }
The <config_document> is a document that specifies the replica set’s configuration. For instance, here’s a
config document for creating a simple 3-member replica set:
{
_id : <setname>,
members : [
{_id : 0, host : <host0>},
{_id : 1, host : <host1>},
{_id : 2, host : <host2>},
]
}
A typical way of running this command is to assign the config document to a variable and then to pass the
document to the rs.initiate() (page 175) helper:
config = {
_id : "my_replica_set",
members : [
{_id : 0, host : "rs1.example.net:27017"},
{_id : 1, host : "rs2.example.net:27017"},
{_id : 2, host : "rs3.example.net", arbiterOnly: true},
]
}
rs.initiate(config)
Notice that omitting the port cause the host to use the default port of 27017. Notice also that you can specify
other options in the config documents such as the arbiterOnly setting in this example.
See also:
2.2. Database Commands
299
MongoDB Reference Manual, Release 2.8.0-rc3
http://docs.mongodb.org/manual/reference/replica-configuration,
http://docs.mongodb.org/manual/administration/replica-sets, and
Reconfiguration (page 177).
Replica
Set
replSetMaintenance
Definition
replSetMaintenance
The replSetMaintenance (page 300) admin command enables or disables the maintenance mode for a
secondary member of a replica set.
The command has the following prototype form:
{ replSetMaintenance: <boolean> }
Behavior Consider the following behavior when running the replSetMaintenance (page 300) command:
• You cannot run the command on the Primary.
• You must run the command against the admin database.
• When enabled replSetMaintenance:
secondary is RECOVERING:
true, the member enters the RECOVERING state. While the
– The member is not accessible for read operations.
– The member continues to sync its oplog from the Primary.
• On secondaries, the compact (page 322) command forces the secondary to enter RECOVERING state. Read
operations issued to an instance in the RECOVERING state will fail. This prevents clients from reading during
the operation. When the operation completes, the secondary returns to:replstate:SECONDARY state.
• See http://docs.mongodb.org/manual/reference/replica-states/ for more information
about replica set member states.
See http://docs.mongodb.org/manual/tutorial/perform-maintence-on-replica-set-members
for an example replica set maintenance procedure to maximize availability during maintenance operations.
replSetReconfig
replSetReconfig
The replSetReconfig (page 300) command modifies the configuration of an existing replica set. You can
use this command to add and remove members, and to alter the options set on existing members. Use the
following syntax:
{ replSetReconfig: <new_config_document>, force: false }
You may also run replSetReconfig (page 300) with the shell’s rs.reconfig() (page 176) method.
Behaviors Be aware of the following replSetReconfig (page 300) behaviors:
• You must issue this command against the admin database of the current primary member of the replica set.
• You can optionally force the replica set to accept the new configuration by specifying force: true. Use
this option if the current member is not primary or if a majority of the members of the set are not accessible.
300
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Warning: Forcing the replSetReconfig (page 300) command can lead to a rollback situation. Use
with caution.
Use the force option to restore a replica set to new servers with different hostnames. This works even if the set
members already have a copy of the data.
• A majority of the set’s members must be operational for the changes to propagate properly.
• This command can cause downtime as the set renegotiates primary-status. Typically this is 10-20 seconds, but
could be as long as a minute or more. Therefore, you should attempt to reconfigure only during scheduled
maintenance periods.
• In some cases, replSetReconfig (page 300) forces the current primary to step down, initiating an election
for primary among the members of the replica set. When this happens, the set will drop all current connections.
replSetReconfig (page 300) obtains a special mutually exclusive lock to prevent more than one
replSetReconfig (page 300) operation from occurring at the same time.
Additional Information http://docs.mongodb.org/manual/reference/replica-configuration,
rs.reconfig() (page 176), and rs.conf() (page 174).
replSetStepDown
Description
replSetStepDown
Forces the primary of the replica set to become a secondary. This initiates an election for primary.
replSetStepDown (page 301) has the following prototype form:
db.runCommand( { replSetStepDown: <seconds> , force: <true|false> } )
replSetStepDown (page 301) has the following fields:
field number replSetStepDown A number of seconds for the member to avoid election to primary.
If you do not specify a value for <seconds>, replSetStepDown (page 301) will attempt to
avoid reelection to primary for 60 seconds from the time that the mongod (page 583) received
the replSetStepDown (page 301) command.
field Boolean force New in version 2.0: Forces the primary to step down even if there are no secondary members that could become primary.
field number secondaryCatchupPeriodSecs The amount of time that the mongod (page 583) will
wait for another secondary in the replica set to catch up to the primary. If no secondary catches
up before this period ends, then the command will fail and the member will not step down, unless
you specify { force: true }.
The default value is 10 seconds, unless you set { force:
default to 0.
true }, which changes the
Behavior
Client Impact replSetStepDown (page 301) forces all clients currently connected to the database to disconnect.
This helps ensure that clients maintain an accurate view of the replica set.
2.2. Database Commands
301
MongoDB Reference Manual, Release 2.8.0-rc3
Secondary Requirements Changed in version 2.8: To avoid rollbacks, replSetStepDown (page 301) will wait
for one secondary to be totally caught up before allowing the primary to step down.
User Operations New in version 2.8.
Before stepping down, replSetStepDown (page 301) will attempt to terminate long running user operations that
would block the primary from stepping down, such as an index build, a write operation or a map-reduce job.
Example The following example specifies that the former primary avoids reelection to primary for 120 seconds:
db.runCommand( { replSetStepDown: 120 } )
replSetSyncFrom
Description
replSetSyncFrom
New in version 2.2.
Explicitly configures which host the current mongod (page 583) pulls oplog entries from. This operation is
useful for testing different patterns and in situations where a set member is not replicating from the desired host.
The replSetSyncFrom (page 302) command has the following form:
{ replSetSyncFrom: "hostname<:port>" }
The replSetSyncFrom (page 302) command has the following field:
field string replSetSyncFrom The name and port number of the replica set member that this member should replicate from. Use the [hostname]:[port] form.
For
more
information
the
use
of
replSetSyncFrom
(page
302),
see
http://docs.mongodb.org/manual/tutorial/configure-replica-set-secondary-sync-target.
resync
resync
The resync (page 302) command forces an out-of-date slave mongod (page 583) instance to re-synchronize
itself. Note that this command is relevant to master-slave replication only. It does not apply to replica sets.
Warning: This command obtains a global write lock and will block other operations until it has completed.
See also:
http://docs.mongodb.org/manual/replication for more information regarding replication.
302
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Sharding Commands
Sharding Commands
Name
addShard (page 303)
checkShardingIndex
(page 304)
cleanupOrphaned
(page 305)
enableSharding
(page 308)
flushRouterConfig
(page 308)
getShardMap
(page 308)
getShardVersion
(page 308)
isdbgrid (page 308)
listShards
(page 309)
medianKey (page 309)
mergeChunks
(page 309)
moveChunk (page 310)
movePrimary
(page 312)
removeShard
(page 312)
setShardVersion
(page 314)
shardCollection
(page 314)
shardingState
(page 315)
splitChunk
(page 315)
splitVector
(page 316)
split (page 316)
unsetSharding
(page 318)
Description
Adds a shard to a sharded cluster.
Internal command that validates index on shard key.
Removes orphaned data with shard key values outside of the ranges of the chunks
owned by a shard.
Enables sharding on a specific database.
Forces an update to the cluster metadata cached by a mongos (page 601).
Internal command that reports on the state of a sharded cluster.
Internal command that returns the config server version.
Verifies that a process is a mongos (page 601).
Returns a list of configured shards.
Deprecated internal command. See splitVector (page 316).
Provides the ability to combine chunks on a single shard.
Internal command that migrates chunks between shards.
Reassigns the primary shard when removing a shard from a sharded cluster.
Starts the process of removing a shard from a sharded cluster.
Internal command to sets the config server version.
Enables the sharding functionality for a collection, allowing the collection to be
sharded.
Reports whether the mongod (page 583) is a member of a sharded cluster.
Internal command to split chunk. Instead use the methods sh.splitFind()
(page 190) and sh.splitAt() (page 190).
Internal command that determines split points.
Creates a new chunk.
Internal command that affects connections between instances in a MongoDB
deployment.
addShard
Definition
addShard
Adds either a database instance or a replica set to a sharded cluster. The optimal configuration is to deploy
shards across replica sets.
Run addShard (page 303) when connected to a mongos (page 601) instance. The command takes the following form when adding a single database instance as a shard:
2.2. Database Commands
303
MongoDB Reference Manual, Release 2.8.0-rc3
{ addShard: "<hostname><:port>", maxSize: <size>, name: "<shard_name>" }
When adding a replica set as a shard, use the following form:
{ addShard: "<replica_set>/<hostname><:port>", maxSize: <size>, name: "<shard_name>" }
The command contains the following fields:
field string addShard The hostname and port of the mongod (page 583) instance to be added as a
shard. To add a replica set as a shard, specify the name of the replica set and the hostname and
port of a member of the replica set.
field integer maxSize The maximum size in megabytes of the shard. If you set maxSize to 0,
MongoDB does not limit the size of the shard.
field string name A name for the shard. If this is not specified, MongoDB automatically provides a
unique name.
The addShard (page 303) command stores shard configuration information in the config database. Always
run addShard (page 303) when using the admin database.
Specify a maxSize when you have machines with different disk capacities, or if you want to limit the amount
of data on some shards. The maxSize constraint prevents the balancer from migrating chunks to the shard
when the value of mem.mapped (page 371) exceeds the value of maxSize.
Considerations
Balancing When you add a shard to a sharded cluster, you affect the balance of chunks among the shards of a cluster
for all existing sharded collections. The balancer will begin migrating chunks so that the cluster will achieve balance.
See http://docs.mongodb.org/manual/core/sharding-balancing for more information.
Hidden Members
Important: You cannot include a hidden member in the seed list provided to addShard (page 303).
Examples The following command adds the database instance running on port 27027 on the host
mongodb0.example.net as a shard:
use admin
db.runCommand({addShard: "mongodb0.example.net:27027"})
Warning: Do not use localhost for the hostname unless your configuration server is also running on
localhost.
The following command adds a replica set as a shard:
use admin
db.runCommand( { addShard: "repl0/mongodb3.example.net:27327"} )
You may specify all members in the replica set. All additional hostnames must be members of the same replica set.
checkShardingIndex
checkShardingIndex
checkShardingIndex (page 304) is an internal command that supports the sharding functionality.
304
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
cleanupOrphaned
Definition
cleanupOrphaned
New in version 2.6.
Deletes from a shard the orphaned documents whose shard key values fall into a single or a single contiguous
range that do not belong to the shard. For example, if two contiguous ranges do not belong to the shard, the
cleanupOrphaned (page 305) examines both ranges for orphaned documents.
cleanupOrphaned (page 305) has the following syntax:
db.runCommand( {
cleanupOrphaned: "<database>.<collection>",
startingAtKey: <minimumShardKeyValue>,
secondaryThrottle: <boolean>,
writeConcern: <document>
} )
cleanupOrphaned (page 305) has the following fields:
field string cleanupOrphaned The namespace, i.e. both the database and the collection name, of
the sharded collection for which to clean the orphaned data.
field document startingFromKey The shard key value that determines the lower bound of the
cleanup range. The default value is MinKey.
If the range that contains the specified startingFromKey value belongs to a chunk owned by
the shard, cleanupOrphaned (page 305) continues to examine the next ranges until it finds
a range not owned by the shard. See Determine Range (page 305) for details.
field boolean secondaryThrottle If true, each delete operation must be replicated to another secondary before the cleanup operation proceeds further. If false, do not wait for replication.
Defaults to false.
Independent of the secondaryThrottle setting,
after the final delete,
cleanupOrphaned (page 305) waits for all deletes to replicate to a majority of replica set
members before returning.
field document writeConcern A document that expresses the write concern that the
secondaryThrottle will use to wait for the secondaries when removing orphaned data.
Any specified writeConcern implies _secondaryThrottle.
Behavior Run cleanupOrphaned (page 305) in the admin database directly on the mongod (page 583) instance
that is the primary replica set member of the shard. Do not run cleanupOrphaned (page 305) on a mongos
(page 601) instance.
You do not need to disable the balancer before running cleanupOrphaned (page 305).
Determine Range The cleanupOrphaned (page 305) command uses the startingFromKey value, if specified, to determine the start of the range to examine for orphaned document:
• If the startingFromKey value falls into a range for a chunk not owned by the shard, cleanupOrphaned
(page 305) begins examining at the start of this range, which may not necessarily be the startingFromKey.
• If the startingFromKey value falls into a range for a chunk owned by the shard, cleanupOrphaned
(page 305) moves onto the next range until it finds a range for a chunk not owned by the shard.
2.2. Database Commands
305
MongoDB Reference Manual, Release 2.8.0-rc3
The cleanupOrphaned (page 305) deletes orphaned documents from the start of the determined range and ends at
the start of the chunk range that belongs to the shard.
Consider the following key space with documents distributed across Shard A and Shard B.
Shard A owns:
• Chunk 1 with the range { x:
minKey } --> { x:
• Chunk 2 with the range { x:
-75 } --> { x:
25 }, and
• Chunk 4 with the range { x:
175 } --> { x:
200 }.
• Chunk 3 with the range { x:
25 } --> { x:
175 } and
• Chunk 5 with the range { x:
200 } --> { x:
-75 },
Shard B owns:
maxKey }.
If on Shard A, the cleanupOrphaned (page 305) command runs with startingFromKey: { x: -70
} or any other value belonging to range for Chunk 1 or Chunk 2, the cleanupOrphaned (page 305) command
examines the Chunk 3 range of { x: 25 } --> { x: 175 } to delete orphaned data.
If on Shard B, the cleanupOrphaned (page 305) command runs with the startingFromKey: { x:
-70 } or any other value belonging to range for Chunk 1, the cleanupOrphaned (page 305) command examines the combined contiguous range for Chunk 1 and Chunk 2, namely { x: minKey } --> { x: 25
} to delete orphaned data.
Required Access On systems running with authorization, you must have clusterAdmin privileges to run
cleanupOrphaned (page 305).
Output
Return Document
following fields:
Each cleanupOrphaned (page 305) command returns a document containing a subset of the
cleanupOrphaned.ok
Equal to 1 on success.
A value of 1 indicates that cleanupOrphaned (page 305) scanned the specified shard key range, deleted any
orphaned documents found in that range, and confirmed that all deletes replicated to a majority of the members
of that shard’s replica set. If confirmation does not arrive within 1 hour, cleanupOrphaned (page 305) times
out.
A value of 0 could indicate either of two cases:
•cleanupOrphaned (page 305) found orphaned documents on the shard but could not delete them.
•cleanupOrphaned (page 305) found and deleted orphaned documents, but could not confirm replication before the 1 hour timeout. In this case, replication does occur, but only after cleanupOrphaned
(page 305) returns.
306
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
cleanupOrphaned.stoppedAtKey
The upper bound of the cleanup range of shard keys. If present, the value corresponds to the lower bound of the
next chunk on the shard. The absence of the field signifies that the cleanup range was the uppermost range for
the shard.
Log Files The cleanupOrphaned (page 305) command prints the number of deleted documents to the mongod
(page 583) log. For example:
m30000| 2013-10-31T15:17:28.972-0400 [conn1] Deleter starting delete for: foo.bar from { _id: -35.0 }
m30000| 2013-10-31T15:17:28.972-0400 [conn1] rangeDeleter deleted 0 documents for foo.bar from { _id:
Examples The following examples run the cleanupOrphaned (page 305) command directly on the primary of
the shard.
Remove Orphaned Documents for a Specific Range For a sharded collection info in the test database, a shard
owns a single chunk with the range: { x: MinKey } --> { x: 10 }.
The shard also contains documents whose shard keys values fall in a range for a chunk not owned by the shard: { x:
10 } --> { x: MaxKey }.
To remove orphaned documents within the { x: 10 } => { x: MaxKey } range, you can specify a
startingFromKey with a value that falls into this range, as in the following example:
use admin
db.runCommand( {
"cleanupOrphaned": "test.info",
"startingFromKey": { x: 10 },
"secondaryThrottle": true
} )
Or you can specify a startingFromKey with a value that falls into the previous range, as in the following:
use admin
db.runCommand( {
"cleanupOrphaned": "test.info",
"startingFromKey": { x: 2 },
"secondaryThrottle": true
} )
Since { x: 2 } falls into a range that belongs to a chunk owned by the shard, cleanupOrphaned (page 305)
examines the next range to find a range not owned by the shard, in this case { x: 10 } => { x: MaxKey
}.
Remove All Orphaned Documents from a Shard cleanupOrphaned (page 305) examines documents from
a single contiguous range of shard keys. To remove all orphaned documents from the shard, you can run
cleanupOrphaned (page 305) in a loop, using the returned stoppedAtKey as the next startingFromKey,
as in the following:
use admin
var nextKey = { };
while ( nextKey = db.runCommand( {
cleanupOrphaned: "test.user",
startingFromKey: nextKey
} ).stoppedAtKey ) {
2.2. Database Commands
307
MongoDB Reference Manual, Release 2.8.0-rc3
printjson(nextKey);
}
enableSharding
enableSharding
The enableSharding (page 308) command enables sharding on a per-database level. Use the following
command form:
{ enableSharding: "<database name>" }
Once you’ve enabled sharding in a database, you can use the shardCollection (page 314) command to
begin the process of distributing data among the shards.
flushRouterConfig
flushRouterConfig
flushRouterConfig (page 308) clears the current cluster information cached by a mongos (page 601)
instance and reloads all sharded cluster metadata from the config database.
This forces an update when the configuration database holds data that is newer than the data cached in the
mongos (page 601) process.
Warning: Do not modify the config data, except as explicitly documented. A config database cannot
typically tolerate manual manipulation.
flushRouterConfig (page 308) is an administrative command that is only available for mongos
(page 601) instances.
New in version 1.8.2.
getShardMap
getShardMap
getShardMap (page 308) is an internal command that supports the sharding functionality.
getShardVersion
getShardVersion
getShardVersion (page 308) is a command that supports sharding functionality and is not part of the stable
client facing API.
isdbgrid
isdbgrid
This command verifies that a process is a mongos (page 601).
If you issue the isdbgrid (page 308) command when connected to a mongos (page 601), the response
document includes the isdbgrid field set to 1. The returned document is similar to the following:
{ "isdbgrid" : 1, "hostname" : "app.example.net", "ok" : 1 }
If you issue the isdbgrid (page 308) command when connected to a mongod (page 583), MongoDB returns
an error document. The isdbgrid (page 308) command is not available to mongod (page 583). The error
document, however, also includes a line that reads "isdbgrid" : 1, just as in the document returned for a
mongos (page 601). The error document is similar to the following:
308
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
{
"errmsg" : "no such cmd: isdbgrid",
"bad cmd" : {
"isdbgrid" : 1
},
"ok" : 0
}
You can instead use the isMaster (page 289) command to determine connection to a mongos (page 601).
When connected to a mongos (page 601), the isMaster (page 289) command returns a document that contains the string isdbgrid in the msg field.
listShards
listShards
Use the listShards (page 309) command to return a list of configured shards. The command takes the
following form:
{ listShards: 1 }
medianKey
medianKey
medianKey (page 309) is an internal command.
mergeChunks
Definition
mergeChunks
For a sharded collection, mergeChunks (page 309) combines contiguous chunk ranges on a shard into a single
chunk. Issue the mergeChunks (page 309) command from a mongos (page 601) instance.
mergeChunks (page 309) has the following form:
db.runCommand( { mergeChunks : <namespace> ,
bounds : [ { <shardKeyField>: <minFieldValue> },
{ <shardKeyField>: <maxFieldValue> } ] } )
For compound shard keys, you must include the full shard key in the bounds specification. If the shard key is
{ x: 1, y: 1 }, mergeChunks (page 309) has the following form:
db.runCommand( { mergeChunks : <namespace> ,
bounds : [ { x: <minValue>, y: <minValue> },
{ x: <maxValue>, y: <maxValue> } ] } )
The mergeChunks (page 309) command has the following fields:
field namespace mergeChunks The fully qualified namespace of the collection where both chunks
exist. Namespaces take form of <database>.<collection>.
field array bounds An array that contains the minimum and maximum key values of the new chunk.
Behavior
Note: Use the mergeChunks (page 309) only in special circumstances. For instance, when cleaning up your
sharded cluster after removing many documents.
In order to successfully merge chunks, the following must be true:
2.2. Database Commands
309
MongoDB Reference Manual, Release 2.8.0-rc3
• In the bounds field, <minkey> and <maxkey> must correspond to the lower and upper bounds of the chunks
to merge.
• The chunks must reside on the same shard.
• The chunks must be contiguous.
mergeChunks (page 309) returns an error if these conditions are not satisfied.
Return Messages On success, mergeChunks (page 309) returns to following document:
{ "ok" : 1 }
Another Operation in Progress mergeChunks (page 309) returns the following error message if another metadata operation is in progress on the chunks (page 683) collection:
errmsg: "The collection's metadata lock is already taken."
If another process, such as balancer process, changes metadata while mergeChunks (page 309) is running, you may
see this error. You can retry the mergeChunks (page 309) operation without side effects.
Chunks on Different Shards If the input chunks are not on the same shard, mergeChunks (page 309) returns an
error similar to the following:
{
"ok" : 0,
"errmsg" : "could not merge chunks, collection test.users does not contain a chunk ending at { use
}
Noncontiguous Chunks If the input chunks are not contiguous, mergeChunks (page 309) returns an error similar
to the following:
{
"ok" : 0,
"errmsg" : "could not merge chunks, collection test.users has more than 2 chunks between [{ userna
}
moveChunk
Definition
moveChunk
Internal administrative command. Moves chunks between shards. Issue the moveChunk (page 310) command
via a mongos (page 601) instance while using the admin database. Use the following forms:
db.runCommand( { moveChunk : <namespace> ,
find : <query> ,
to : <string>,
_secondaryThrottle : <boolean>,
writeConcern: <document>,
_waitForDelete : <boolean> } )
Alternately:
310
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.runCommand( { moveChunk : <namespace> ,
bounds : <array> ,
to : <string>,
_secondaryThrottle : <boolean>,
writeConcern: <document>,
_waitForDelete : <boolean> } )
The moveChunk (page 310) command has the following fields:
field string moveChunk The namespace of the collection where the chunk exists. Specify the collection’s full namespace, including the database name.
field document find An equality match on the shard key that specifies the shard-key value of the
chunk to move. Specify either the bounds field or the find field but not both. Do not use the
find field to select chunks in collections that use a hashed shard key.
field array bounds The bounds of a specific chunk to move. The array must consist of two documents that specify the lower and upper shard key values of a chunk to move. Specify either the
bounds field or the find field but not both. Use bounds to select chunks in collections that
use a hashed shard key.
field string to The name of the destination shard for the chunk.
field Boolean secondaryThrottle Defaults to true. When true, the balancer waits for replication
to secondaries when it copies and deletes data during chunk migrations. For details, see shardedcluster-config-secondary-throttle.
field document writeConcern A document that expresses the write concern that the
_secondaryThrottle will use to wait for secondaries during the chunk migration. Any
specified writeConcern implies _secondaryThrottle and will take precedent over a
contradictory _secondaryThrottle setting.
field Boolean _waitForDelete Internal option for testing purposes. The default is false. If set to
true, the delete phase of a moveChunk (page 310) operation blocks.
The value of bounds takes the form:
[ { hashedField : <minValue> } ,
{ hashedField : <maxValue> } ]
The chunk migration section describes how chunks move between shards on MongoDB.
See also:
split (page 316), sh.moveChunk() (page 187), sh.splitAt() (page 190), and sh.splitFind()
(page 190).
Considerations Only use the moveChunk (page 310) in special circumstances such as preparing your sharded cluster for an initial ingestion of data, or a large bulk import operation.
In most cases allow the balancer to create and balance chunks in sharded clusters.
See
http://docs.mongodb.org/manual/tutorial/create-chunks-in-sharded-cluster
for
more information.
Behavior
Indexes Changed in version 2.8.0: In previous versions, moveChunk (page 310) would build indexes as part of the
migrations.
2.2. Database Commands
311
MongoDB Reference Manual, Release 2.8.0-rc3
moveChunk (page 310) requires that all indexes exist on the target (i.e. to ) shard before migration and returns an
error if a required index does not exist.
Meta Data Error moveChunk (page 310) returns the following error message if another metadata operation is in
progress on the chunks (page 683) collection:
errmsg: "The collection's metadata lock is already taken."
If another process, such as a balancer process, changes meta data while moveChunk (page 310) is running, you may
see this error. You may retry the moveChunk (page 310) operation without side effects.
movePrimary
movePrimary
In a sharded cluster, movePrimary (page 312) reassigns the primary shard which holds all un-sharded collections in the database. movePrimary (page 312) first changes the primary shard in the cluster metadata, and
then migrates all un-sharded collections to the specified shard. Use the command with the following form:
{ movePrimary : "test", to : "shard0001" }
When the command returns, the database’s primary location will shift to the designated shard. To fully decommission a shard, use the removeShard (page 312) command.
movePrimary (page 312) is an administrative command that is only available for mongos (page 601) instances.
Considerations
Behavior Avoid accessing an un-sharded collection during migration. movePrimary (page 312) does not prevent
reading and writing during its operation, and such actions yield undefined behavior.
movePrimary (page 312) may take significant time to complete, and you should plan for this unavailability.
movePrimary (page 312) will fail if the destination shard contains a conflicting collection name. This may occur if
documents are written to an un-sharded collection while the collection is moved away, and later the original primary
shard is restored.
Use If you use the movePrimary (page 312) command to move un-sharded collections, you must either restart all
mongos (page 601) instances, or use the flushRouterConfig (page 308) command on all mongos (page 601)
instances before writing any data to the cluster. This action notifies the mongos (page 601) of the new shard for the
database.
If you do not update the mongos (page 601) instances’ metadata cache after using movePrimary (page 312), the
mongos (page 601) may not write data to the correct shard. To recover, you must manually intervene.
Additional Information See http://docs.mongodb.org/manual/tutorial/remove-shards-from-cluster
for a complete procedure.
removeShard
removeShard
Removes a shard from a sharded cluster. When you run removeShard (page 312), MongoDB first moves the
shard’s chunks to other shards in the cluster. Then MongoDB removes the shard.
312
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Behavior
Access Requirements You must run removeShard (page 312) while connected to a mongos (page 601). Issue
the command against the admin database or use the sh._adminCommand() (page 182) helper.
If you have authorization enabled, you must have the clusterManager role or any role that includes the
removeShard action.
Database Migration Requirements Each database in a sharded cluster has a primary shard. If the shard you
want to remove is also the primary of one of the cluster’s databases, then you must manually move the databases
to a new shard after migrating all data from the shard. See the movePrimary (page 312) command and the
http://docs.mongodb.org/manual/tutorial/remove-shards-from-cluster for more information.
Example From the mongo (page 610) shell, the removeShard (page 312) operation resembles the following:
use admin
db.runCommand( { removeShard : "bristol01" } )
Replace bristol01 with the name of the shard to remove. When you run removeShard (page 312), the command
returns immediately, with the following message:
{
"msg" : "draining started successfully",
"state" : "started",
"shard" : "bristol01",
"ok" : 1
}
The balancer begins migrating chunks from the shard named bristol01 to other shards in the cluster. These
migrations happens slowly to avoid placing undue load on the overall cluster.
If you run the command again, removeShard (page 312) returns the following progress output:
{
"msg" : "draining ongoing",
"state" : "ongoing",
"remaining" : {
"chunks" : 23,
"dbs" : 1
},
"ok" : 1
}
The remaining document specifies how many chunks and databases remain on the shard.
Use
db.printShardingStatus() (page 122) to list the databases that you must move from the shard. Use the
movePrimary (page 312) to move databases.
After removing all chunks and databases from the shard, you can issue removeShard (page 312) again see the
following:
{
"msg" : "removeshard completed successfully",
"state" : "completed",
"shard" : "bristol01",
"ok" : 1
}
2.2. Database Commands
313
MongoDB Reference Manual, Release 2.8.0-rc3
setShardVersion
setShardVersion
setShardVersion (page 314) is an internal command that supports sharding functionality.
shardCollection
Definition
shardCollection
Enables a collection for sharding and allows MongoDB to begin distributing data among shards. You must run
enableSharding (page 308) on a database before running the shardCollection (page 314) command.
shardCollection (page 314) has the following form:
{ shardCollection: "<database>.<collection>", key: <shardkey> }
shardCollection (page 314) has the following fields:
field string shardCollection The namespace
<database>.<collection>.
of
the
collection
to
shard
in
the
form
field document key The index specification document to use as the shard key. The index must exist
prior to the shardCollection (page 314) command, unless the collection is empty. If the
collection is empty, in which case MongoDB creates the index prior to sharding the collection.
New in version 2.4: The key may be in the form { field : "hashed" }, which will use
the specified field as a hashed shard key.
field Boolean unique When true, the unique option ensures that the underlying index enforces
a unique constraint. Hashed shard keys do not support unique constraints.
field integer numInitialChunks Specifies the number of chunks to create initially when sharding an
empty collection with a hashed shard key. MongoDB will then create and balance chunks across
the cluster. The numInitialChunks must be less than 8192 per shard. If the collection is
not empty, numInitialChunks has no effect.
Considerations
Use Do not run more than one shardCollection (page 314) command on the same collection at the same time.
MongoDB provides no method to deactivate sharding for a collection after calling shardCollection (page 314).
Additionally, after shardCollection (page 314), you cannot change shard keys or modify the value of any field
used in your shard key index.
Shard Keys Choosing the best shard key to effectively distribute load among your shards requires some planning.
Review sharding-shard-key regarding choosing a shard key.
Hashed Shard Keys New in version 2.4.
Hashed shard keys use a hashed index of a single field as the shard key.
Note: If chunk migrations are in progress while creating a hashed shard key collection, the initial chunk distribution
may be uneven until the balancer automatically balances the collection.
314
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Example The following operation enables sharding for the people collection in the records database and uses
the zipcode field as the shard key:
db.runCommand( { shardCollection: "records.people", key: { zipcode: 1 } } )
Additional
Information http://docs.mongodb.org/manual/sharding,
http://docs.mongodb.org/manual/core/sharding, and http://docs.mongodb.org/manual/tutorial/dep
shardingState
shardingState
shardingState (page 315) is an admin command that reports if mongod (page 583) is a member of a
sharded cluster. shardingState (page 315) has the following prototype form:
{ shardingState: 1 }
For shardingState (page 315) to detect that a mongod (page 583) is a member of a sharded cluster, the
mongod (page 583) must satisfy the following conditions:
1.the mongod (page 583) is a primary member of a replica set, and
2.the mongod (page 583) instance is a member of a sharded cluster.
If shardingState (page 315) detects that a mongod (page 583) is a member of a sharded cluster,
shardingState (page 315) returns a document that resembles the following prototype:
{
"enabled" : true,
"configServer" : "<configdb-string>",
"shardName" : "<string>",
"shardHost" : "string:",
"versions" : {
"<database>.<collection>" : Timestamp(<...>),
"<database>.<collection>" : Timestamp(<...>)
},
"ok" : 1
}
Otherwise, shardingState (page 315) will return the following document:
{ "note" : "from execCommand", "ok" : 0, "errmsg" : "not master" }
The response from shardingState (page 315) when used with a config server is:
{ "enabled": false, "ok": 1 }
Note: mongos (page 601) instances do not provide the shardingState (page 315).
Warning: This command obtains a write lock on the affected database and will block other operations until
it has completed; however, the operation is typically short lived.
splitChunk
Definition
2.2. Database Commands
315
MongoDB Reference Manual, Release 2.8.0-rc3
splitChunk
An internal administrative command. To split chunks, use the sh.splitFind() (page 190) and
sh.splitAt() (page 190) functions in the mongo (page 610) shell.
Warning: Be careful when splitting data in a sharded collection to create new chunks. When you shard a
collection that has existing data, MongoDB automatically creates chunks to evenly distribute the collection.
To split data effectively in a sharded cluster you must consider the number of documents in a chunk and the
average document size to create a uniform chunk size. When chunks have irregular sizes, shards may have
an equal number of chunks but have very different data sizes. Avoid creating splits that lead to a collection
with differently sized chunks.
See also:
moveChunk (page 310) and sh.moveChunk() (page 187).
The splitChunk (page 315) command takes a document with the following fields:
field string ns The complete namespace of the chunk to split.
field document keyPattern The shard key.
field document min The lower bound of the shard key for the chunk to split.
field document max The upper bound of the shard key for the chunk to split.
field string from The shard that owns the chunk to split.
field document splitKeys The split point for the chunk.
field document shardId The shard.
splitVector
splitVector
Is an internal command that supports meta-data operations in sharded clusters.
split
Definition
split
Splits a chunk in a sharded cluster into two chunks.
The mongos (page 601) instance splits and manages chunks automatically, but for exceptional circumstances the
split (page 316) command does allow administrators to manually create splits.
See
http://docs.mongodb.org/manual/tutorial/split-chunks-in-sharded-cluster
for information on these circumstances, and on the MongoDB shell commands that wrap split (page 316).
The split (page 316) command uses the following form:
db.adminCommand( { split: <database>.<collection>,
<find|middle|bounds> } )
The split (page 316) command takes a document with the following fields:
field string split The name of the collection where the chunk exists. Specify the collection’s full
namespace, including the database name.
field document find An query statement that specifies an equality match on the shard key. The
match selects the chunk that contains the specified document. You must specify only one of the
following: find, bounds, or middle.
316
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
You cannot use the find option on an empty collection.
field array bounds New in version 2.4: The bounds of a chunk to split. bounds applies to chunks
in collections partitioned using a hashed shard key. The parameter’s array must consist of two
documents specifying the lower and upper shard-key values of the chunk. The values must match
the minimum and maximum values of an existing chunk. Specify only one of the following:
find, bounds, or middle.
You cannot use the bounds option on an empty collection.
field document middle The document to use as the split point to create two chunks. split
(page 316) requires one of the following options: find, bounds, or middle.
Considerations When used with either the find or the bounds option, the split (page 316) command splits the
chunk along the median. As such, the command cannot use the find or the bounds option to split an empty chunk
since an empty chunk has no median.
To create splits in empty chunks, use either the middle option with the split (page 316) command or use the
splitAt command.
Command Formats To create a chunk split, connect to a mongos (page 601) instance, and issue the following
command to the admin database:
db.adminCommand( { split: <database>.<collection>,
find: <document> } )
Or:
db.adminCommand( { split: <database>.<collection>,
middle: <document> } )
Or:
db.adminCommand( { split: <database>.<collection>,
bounds: [ <lower>, <upper> ] } )
To create a split for a collection that uses a hashed shard key, use the bounds parameter. Do not use the middle
parameter for this purpose.
Warning: Be careful when splitting data in a sharded collection to create new chunks. When you shard a
collection that has existing data, MongoDB automatically creates chunks to evenly distribute the collection. To
split data effectively in a sharded cluster you must consider the number of documents in a chunk and the average
document size to create a uniform chunk size. When chunks have irregular sizes, shards may have an equal number
of chunks but have very different data sizes. Avoid creating splits that lead to a collection with differently sized
chunks.
See also:
moveChunk (page 310), sh.moveChunk() (page 187), sh.splitAt() (page 190), and sh.splitFind()
(page 190), which wrap the functionality of split (page 316).
Examples The following sections provide examples of the split (page 316) command.
Split a Chunk in Half
2.2. Database Commands
317
MongoDB Reference Manual, Release 2.8.0-rc3
db.runCommand( { split : "test.people", find : { _id : 99 } } )
The split (page 316) command identifies the chunk in the people collection of the test database, that holds
documents that match { _id : 99 }. split (page 316) does not require that a match exist, in order to identify
the appropriate chunk. Then the command splits it into two chunks of equal size.
Note: split (page 316) creates two equal chunks by range as opposed to size, and does not use the selected point
as a boundary for the new chunks
Define an Arbitrary Split Point To define an arbitrary split point, use the following form:
db.runCommand( { split : "test.people", middle : { _id : 99 } } )
The split (page 316) command identifies the chunk in the people collection of the test database, that would
hold documents matching the query { _id : 99 }. split (page 316) does not require that a match exist, in
order to identify the appropriate chunk. Then the command splits it into two chunks, with the matching document as
the lower bound of one of the split chunks.
This form is typically used when pre-splitting data in a collection.
Split a Chunk Using Values of a Hashed Shard Key This example uses the hashed shard key userid in a
people collection of a test database. The following command uses an array holding two single-field documents to
represent the minimum and maximum values of the hashed shard key to split the chunk:
db.runCommand( { split: "test.people",
bounds : [ { userid: NumberLong("-5838464104018346494") },
{ userid: NumberLong("-5557153028469814163") }
] } )
Note: MongoDB uses the 64-bit NumberLong type to represent the hashed value.
Use sh.status() (page 191) to see the existing bounds of the shard keys.
Metadata Lock Error If another process in the mongos (page 601), such as a balancer process, changes metadata
while split (page 316) is running, you may see a metadata lock error.
errmsg: "The collection's metadata lock is already taken."
This message indicates that the split has failed with no side effects. Retry the split (page 316) command.
unsetSharding
unsetSharding
unsetSharding (page 318) is an internal command that supports sharding functionality.
See also:
http://docs.mongodb.org/manual/sharding for more information about MongoDB’s sharding functionality.
318
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Instance Administration Commands
Administration Commands
Name
clean (page 319)
cloneCollectionAsCapped
(page 319)
cloneCollection (page 320)
clone (page 320)
collMod (page 321)
compact (page 322)
connPoolSync (page 325)
connectionStatus (page 325)
convertToCapped (page 326)
copydb (page 326)
createIndexes (page 330)
create (page 333)
dropDatabase (page 334)
dropIndexes (page 335)
drop (page 335)
filemd5 (page 335)
fsync (page 336)
getParameter (page 337)
listCollections (page 338)
listIndexes (page 338)
logRotate (page 339)
reIndex (page 340)
renameCollection (page 340)
repairCursor (page 341)
repairDatabase (page 341)
setParameter (page 343)
shutdown (page 344)
touch (page 344)
Description
Internal namespace administration command.
Copies a non-capped collection as a new capped collection.
Copies a collection from a remote host to the current host.
Copies a database from a remote host to the current host.
Add flags to collection to modify the behavior of MongoDB.
Defragments a collection and rebuilds the indexes.
Internal command to flush connection pool.
Reports the authentication state for the current connection.
Converts a non-capped collection to a capped collection.
Copies a database from a remote host to the current host.
Builds one or more indexes for a collection.
Creates a collection and sets collection parameters.
Removes the current database.
Removes indexes from a collection.
Removes the specified collection from the database.
Returns the md5 hash for files stored using GridFS.
Flushes pending writes to the storage layer and locks the database to
allow backups.
Retrieves configuration options.
Returns a list of collections in the current database.
Lists all indexes for a collection.
Rotates the MongoDB logs to prevent a single file from taking too
much space.
Rebuilds all indexes on a collection.
Changes the name of an existing collection.
Returns a cursor that iterates over all valid documents in a collection.
Repairs any errors and inconsistencies with the data storage.
Modifies configuration options.
Shuts down the mongod (page 583) or mongos (page 601) process.
Loads documents and indexes from data storage to memory.
clean
clean
clean (page 319) is an internal command.
Warning: This command obtains a write lock on the affected database and will block other operations until
it has completed.
cloneCollectionAsCapped
cloneCollectionAsCapped
The cloneCollectionAsCapped (page 319) command creates a new capped collection from an existing, non-capped collection within the same database. The operation does not affect the original non-capped
collection.
The command has the following syntax:
2.2. Database Commands
319
MongoDB Reference Manual, Release 2.8.0-rc3
{ cloneCollectionAsCapped: <existing collection>, toCollection: <capped collection>, size: <capp
The command copies an existing collection and creates a new capped collection with a maximum size specified by the capped size in bytes. The name of the new capped collection must be distinct
and cannot be the same as that of the original existing collection. To replace the original non-capped collection
with a capped collection, use the convertToCapped (page 326) command.
During the cloning, the cloneCollectionAsCapped (page 319) command exhibit the following behavior:
•MongoDB will transverse the documents in the original collection in natural order as they’re loaded.
•If the capped size specified for the new collection is smaller than the size of the original uncapped
collection, then MongoDB will begin overwriting earlier documents in insertion order, which is first in,
first out (e.g “FIFO”).
cloneCollection
Definition
cloneCollection
Copies a collection from a remote mongod (page 583) instance to the current mongod (page 583) instance.
cloneCollection (page 320) creates a collection in a database with the same name as the remote collection’s database. cloneCollection (page 320) takes the following form:
{ cloneCollection: "<namespace>", from: "<hostname>", query: { <query> } }
Important: You cannot clone a collection through a mongos (page 601) but must connect directly to the
mongod (page 583) instance.
cloneCollection (page 320) has the following fields:
field string cloneCollection The namespace of the collection to rename. The namespace is a combination of the database name and the name of the collection.
field string from Specify a resolvable hostname and optional port number of the remote server
where the specified collection resides.
field document query A query that filters the documents in the remote collection that
cloneCollection (page 320) will copy to the current database.
Example
{ cloneCollection: "users.profiles", from: "mongodb.example.net:27017", query: { active: true } }
This operation copies the profiles collection from the users database on the server at
mongodb.example.net. The operation only copies documents that satisfy the query { active: true }.
cloneCollection (page 320) always copies indexes. The query arguments is optional.
If, in the above example, the profiles collection exists in the users database, then MongoDB appends documents
from the remote collection to the destination collection.
clone
clone
The clone (page 320) command clones a database from a remote MongoDB instance to the current host.
clone (page 320) copies the database on the remote instance with the same name as the current database. The
command takes the following form:
320
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
{ clone: "db1.example.net:27017" }
Replace db1.example.net:27017 above with the resolvable hostname for the MongoDB instance you
wish to copy from. Note the following behaviors:
•clone (page 320) can copy from a non-primary member of a replica set.
•clone (page 320) does not snapshot the database. If any clients update the database you’re copying at
any point during the clone operation, the resulting database may be inconsistent.
•You must run clone (page 320) on the destination server.
•The destination database will be locked periodically during the clone (page 320) operation. In other
words, clone (page 320) will occasionally yield to allow other operations on the database to complete.
See copydb (page 326) for similar functionality with greater flexibility.
collMod
Definition
collMod
New in version 2.2.
collMod (page 321) makes it possible to add flags to a collection to modify the behavior of MongoDB. Flags
include usePowerOf2Sizes (page 322) and index (page 321). The command takes the following prototype
form:
db.runCommand( {"collMod" : <collection> , "<flag>" : <value> } )
In this command substitute <collection> with the name of a collection in the current database, and <flag>
and <value> with the flag and value you want to set.
Use the userFlags (page 349) field in the db.collection.stats() (page 71) output to check enabled
collection flags.
Flags
TTL Collection Expiration Time
index
The index (page 321) flag changes the expiration time of a TTL Collection.
Specify the key and new expiration time with a document of the form:
{keyPattern: <index_spec>, expireAfterSeconds: <seconds> }
In this example, <index_spec> is an existing index in the collection and seconds is the number of seconds
to subtract from the current time.
On success collMod (page 321) returns a document with fields expireAfterSeconds_old and
expireAfterSeconds_new set to their respective values.
On failure, collMod (page 321) returns a document with no expireAfterSeconds field to
update if there is no existing expireAfterSeconds field or cannot find index { **key**:
1.0 } for ns **namespace** if the specified keyPattern does not exist.
2.2. Database Commands
321
MongoDB Reference Manual, Release 2.8.0-rc3
Record Allocation
Storage Engine Specific Feature
The power of two allocation strategy and noPadding (page 322) feature are only available with the mmapv1 storage
engine.
Disable All Record Padding
noPadding
New in version 2.8.0.
Disables all record padding. All records allocations are the size needed to hold the documents. All updates that
require the document to grow will require a new allocation.
Only use noPadding (page 322) for collections where there are no delete operations or update operations that
cause documents to grow.
Powers of Two Record Allocation
usePowerOf2Sizes
Deprecated since version 2.8: All collections have the usePowerOf2Sizes (page 322) allocation strategy by default unless you specify the noPadding option to db.createCollection() (page 104) or
set noPadding (page 322).
The usePowerOf2Sizes (page 322) flag changes the method that MongoDB uses to allocate space on disk
for documents in this collection. By setting usePowerOf2Sizes (page 322), yousthat are powers of 2 (e.g.
32, 64, 128, 256, 512...16777216.) The smallest allocation for a document is 32 bytes.
With usePowerOf2Sizes (page 322), MongoDB will be able to more effectively reuse space.
With usePowerOf2Sizes (page 322), MongoDB allocates records that have power of 2 sizes until record
sizes equal 4 megabytes. For records larger than 4 megabytes with usePowerOf2Sizes (page 322) set,
mongod (page 583) will allocate records in full megabytes by rounding up to the nearest megabyte.
Example: Change Expiration Value for Indexes To update the expiration value for a collection named sessions
indexed on a lastAccess field from 30 minutes to 60 minutes, use the following operation:
db.runCommand({collMod: "sessions",
index: {keyPattern: {lastAccess:1},
expireAfterSeconds: 3600}})
Which will return the document:
{ "expireAfterSeconds_old" : 1800, "expireAfterSeconds_new" : 3600, "ok" : 1 }
compact
Definition
compact
New in version 2.0.
Rewrites and defragments all data in a collection, as well as all of the indexes on that collection. compact
(page 322) has the following form:
{ compact: <collection name> }
compact (page 322) has the following fields:
322
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
field string compact The name of the collection.
field boolean force If true, compact (page 322) can run on the primary in a replica set. If
false, compact (page 322) returns an error when run on a primary, because the command
blocks all other activity. Beginning with version 2.2, compact (page 322) blocks activity only
for the database it is compacting.
field number paddingFactor Describes the record size allocated for each document as a factor of
the document size for all records compacted during the compact (page 322) operation. The
paddingFactor does not affect the padding of subsequent record allocations after compact
(page 322) completes. For more information, see paddingFactor (page 323).
field integer paddingBytes Sets the padding as an absolute number of bytes for all records compacted during the compact (page 322) operation. After compact (page 322) completes,
paddingBytes does not affect the padding of subsequent record allocations. For more information, see paddingBytes (page 323).
compact (page 322) is similar to repairDatabase (page 341); however, repairDatabase (page 341)
operates on an entire database.
Warning: Always have an up-to-date backup before performing server maintenance such as the compact
(page 322) operation.
paddingFactor New in version 2.2.
The paddingFactor field takes the following range of values:
• Default: 1.0
• Minimum: 1.0 (no padding)
• Maximum: 4.0
If your updates increase the size of the documents, padding will increase the amount of space allocated to each
document and avoid expensive document relocation operations within the data files.
You can calculate the padding size by subtracting the document size from the record size or, in terms of the
paddingFactor, by subtracting 1 from the paddingFactor:
padding size = (paddingFactor - 1) * <document size>.
For example, a paddingFactor of 1.0 specifies a padding size of 0 whereas a paddingFactor of 1.2 specifies
a padding size of 0.2 or 20 percent (20%) of the document size.
With the following command, you can use the paddingFactor option of the compact (page 322) command to
set the record size to 1.1 of the document size, or a padding factor of 10 percent (10%):
db.runCommand ( { compact: '<collection>', paddingFactor: 1.1 } )
compact (page 322) compacts existing documents but does not reset paddingFactor statistics for the collection.
After the compact (page 322) MongoDB will use the existing paddingFactor when allocating new records for
documents in this collection.
paddingBytes New in version 2.2.
Specifying paddingBytes can be useful if your documents start small but then increase in size significantly. For
example, if your documents are initially 40 bytes long and you grow them by 1KB, using paddingBytes: 1024
might be reasonable since using paddingFactor: 4.0 would specify a record size of 160 bytes (4.0 times
the initial document size), which would only provide a padding of 120 bytes (i.e. record size of 160 bytes minus the
document size).
2.2. Database Commands
323
MongoDB Reference Manual, Release 2.8.0-rc3
With the following command, you can use the paddingBytes option of the compact (page 322) command to set
the padding size to 100 bytes on the collection named by <collection>:
db.runCommand ( { compact: '<collection>', paddingBytes: 100 } )
Behaviors
Blocking In MongoDB 2.2, compact (page 322) blocks activities only for its database. Prior to 2.2, the command
blocked all activities.
You may view the intermediate progress either by viewing the mongod (page 583) log file or by running the
db.currentOp() (page 105) in another shell instance.
Operation Termination If you terminate the operation with the db.killOp() (page 119) method or restart the
server before the compact (page 322) operation has finished:
• If you have journaling enabled, the data remains valid and usable, regardless of the state of the compact
(page 322) operation. You may have to manually rebuild the indexes.
• If you do not have journaling enabled and the mongod (page 583) or compact (page 322) terminates during
the operation, it is impossible to guarantee that the data is in a valid state.
• In either case, much of the existing free space in the collection may become un-reusable. In this scenario, you
should rerun the compaction to completion to restore the use of this free space.
Disk Space compact (page 322) generally uses less disk space than repairDatabase (page 341) and is faster.
However, the compact (page 322) command is still slow and blocks other database use. Only use compact
(page 322) during scheduled maintenance periods.
compact (page 322) requires up to 2 gigabytes of additional disk space while running. Unlike repairDatabase
(page 341), compact (page 322) does not free space on the file system.
To see how the storage space changes for the collection, run the collStats (page 348) command before and after
compaction.
Size and Number of Data Files compact (page 322) may increase the total size and number of your data files,
especially when run for the first time. However, this will not increase the total collection storage space since storage
size is the amount of data allocated within the database files, and not the size/number of the files on the file system.
Replica Sets compact (page 322) commands do not replicate to secondaries in a replica set:
• Compact each member separately.
• Ideally run compact (page 322) on a secondary. See option force:true above for information regarding
compacting the primary.
• On secondaries, the compact (page 322) command forces the secondary to enter RECOVERING state. Read
operations issued to an instance in the RECOVERING state will fail. This prevents clients from reading during
the operation. When the operation completes, the secondary returns to:replstate:SECONDARY state.
• See http://docs.mongodb.org/manual/reference/replica-states/ for more information
about replica set member states.
See http://docs.mongodb.org/manual/tutorial/perform-maintence-on-replica-set-members
for an example replica set maintenance procedure to maximize availability during maintenance operations.
324
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Sharded Clusters compact (page 322) is a command issued to a mongod (page 583). In a sharded environment,
run compact (page 322) on each shard separately as a maintenance operation.
You cannot issue compact (page 322) against a mongos (page 601) instance.
Capped Collections It is not possible to compact capped collections because they don’t have padding, and documents cannot grow in these collections. However, the documents of a capped collection are not subject to fragmentation.
Index Building New in version 2.6.
mongod (page 583) rebuilds all indexes in parallel following the compact (page 322) operation.
connPoolSync
connPoolSync
connPoolSync (page 325) is an internal command.
connectionStatus New in version 2.4.0.
Definition
connectionStatus
Returns information about the current connection, specifically the state of authenticated users and their available
permissions.
Output
connectionStatus.authInfo
A document with data about the authentication state of the current collection, including users and available
permissions.
connectionStatus.authinfo.authenticatedUsers
An array with documents for each authenticated user.
connectionStatus.authInfo.authenticatedUsers[n].user
The user’s name.
connectionStatus.authInfo.authenticatedUsers[n].db
The database associated with the user’s credentials.
connectionStatus.authinfo.authenticatedUserRoles
An array with documents for each role granted to the current connection:
connectionStatus.authinfo.authenticatedUserRoles[n].role
The definition of the current roles associated with the current authenticated users.
See
http://docs.mongodb.org/manual/reference/built-in-roles
and
http://docs.mongodb.org/manual/reference/privilege-actions for more information.
connectionStatus.authinfo.authenticatedUserRoles[n].db
The database to which role (page 325) applies.
connectionStatus.ok
The return value for the command. A value of 1 indicates success.
2.2. Database Commands
325
MongoDB Reference Manual, Release 2.8.0-rc3
convertToCapped
convertToCapped
The convertToCapped (page 326) command converts an existing, non-capped collection to a capped collection within the same database.
The command has the following syntax:
{ convertToCapped: <collection>, size: <capped size> }
convertToCapped (page 326) takes an existing collection (<collection>) and transforms it into a
capped collection with a maximum size in bytes, specified by the size argument (<capped size>).
During the conversion process, the convertToCapped (page 326) command exhibits the following behavior:
•MongoDB traverses the documents in the original collection in natural order and loads the documents into
a new capped collection.
•If the capped size specified for the capped collection is smaller than the size of the original uncapped
collection, then MongoDB will overwrite documents in the capped collection based on insertion order, or
first in, first out order.
•Internally, to convert the collection, MongoDB uses the following procedure
–cloneCollectionAsCapped (page 319) command creates the capped collection and imports the
data.
–MongoDB drops the original collection.
–renameCollection (page 340) renames the new capped collection to the name of the original
collection.
Note: MongoDB does not support the convertToCapped (page 326) command in a sharded cluster.
Warning: The convertToCapped (page 326) will not recreate indexes from the original collection on
the new collection, other than the index on the _id field. If you need indexes on this collection you will
need to create these indexes after the conversion is complete.
See also:
create (page 333)
copydb
Definition
copydb
Copies a database from a remote host to the current host or copies a database to another database within the
current host. Run copydb (page 326) in the admin database of the destination server with the following
syntax:
{ copydb: 1,
fromhost: <hostname>,
fromdb: <database>,
todb: <database>,
slaveOk: <bool>,
username: <username>,
nonce: <nonce>,
key: <key> }
326
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
copydb (page 326) accepts the following options:
field string fromhost Hostname of the remote source mongod (page 583) instance.
fromhost to copy from one database to another on the same server.
Omit
field string fromdb Name of the source database.
field string todb Name of the target database.
field boolean slaveOk Set slaveOK to true to allow copydb (page 326) to copy data from secondary members as well as the primary. fromhost must also be set.
field string username The username credentials on the fromhost MongoDB deployment.
field string nonce A single use shared secret generated on the remote server, i.e. fromhost, using
the copydbgetnonce (page 264) command. See Authentication (page 328) for details.
field string key A hash of the password used for authentication. See Authentication (page 328) for
details.
The mongo (page 610) shell provides the db.copyDatabase() (page 102) wrapper for the copydb
(page 326) command.
Behavior Be aware of the following properties of copydb (page 326):
• copydb (page 326) runs on the destination mongod (page 583) instance, i.e. the host receiving the copied
data.
• If the destination mongod (page 583) has authorization enabled, copydb (page 326) must specify
the credentials of a user present in the source database who has the privileges described in Required Access
(page 102).
• copydb (page 326) creates the target database if it does not exist.
• copydb (page 326) requires enough free disk space on the host instance for the copied database. Use the
db.stats() (page 126) operation to check the size of the database on the source mongod (page 583) instance.
• copydb (page 326) and clone (page 320) 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 divergent data sets.
• copydb (page 326) does not lock the destination server during its operation, so the copy will occasionally yield
to allow other operations to complete.
Required Access Changed in version 2.6.
On systems running with authorization, the copydb (page 326) command requires the following authorization
on the target and source databases.
Source Database (fromdb)
Source is non-admin Database If the source database is a non-admin database, you must have privileges that
specify find action on the source database, and find action on the system.js collection in the source database.
For example:
{ resource: { db: "mySourceDB", collection: "" }, actions: [ "find" ] }
{ resource: { db: "mySourceDB", collection: "system.js" }, actions: [ "find" ] }
If the source database is on a remote server, you also need the find action on the system.indexes and
system.namespaces collections in the source database; e.g.
2.2. Database Commands
327
MongoDB Reference Manual, Release 2.8.0-rc3
{ resource: { db: "mySourceDB", collection: "system.indexes" }, actions: [ "find" ] }
{ resource: { db: "mySourceDB", collection: "system.namespaces" }, actions: [ "find" ] }
Source is admin Database If the source database is the admin database, you must have privileges that specify
find action on the admin database, and find action on the system.js, system.users, system.roles,
and system.version collections in the admin database. For example:
{
{
{
{
{
resource:
resource:
resource:
resource:
resource:
{
{
{
{
{
db:
db:
db:
db:
db:
"admin",
"admin",
"admin",
"admin",
"admin",
collection:
collection:
collection:
collection:
collection:
"" }, actions: [ "find" ] }
"system.js" }, actions: [ "find" ] }
"system.users" }, actions: [ "find" ] }
"system.roles" }, actions: [ "find" ] }
"system.version" }, actions: [ "find" ] }
If the source database is on a remote server, the you also need the find action on the system.indexes and
system.namespaces collections in the admin database; e.g.
{ resource: { db: "admin", collection: "system.indexes" }, actions: [ "find" ] }
{ resource: { db: "admin", collection: "system.namespaces" }, actions: [ "find" ] }
Source Database is on a Remote Server If copying from a remote server and the remote server has authentication enabled, you must authenticate to the remote host as a user with the proper authorization. See Authentication
(page 328).
Target Database (todb)
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 system.js
collection in the target database. For example:
{ resource: { db: "myTargetDB", collection: "" }, actions: [ "insert", "createIndex" ] }
{ resource: { db: "myTargetDB", collection: "system.js" }, 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 system.js,
system.users, system.roles, and system.version collections in the target database. For example:
{
{
{
{
{
resource:
resource:
resource:
resource:
resource:
{
{
{
{
{
db:
db:
db:
db:
db:
"myTargetDB",
"myTargetDB",
"myTargetDB",
"myTargetDB",
"myTargetDB",
collection:
collection:
collection:
collection:
collection:
"" }, actions: [ "insert", "createIndex" ] },
"system.js" }, actions: [ "insert" ] },
"system.users" }, actions: [ "insert" ] },
"system.roles" }, actions: [ "insert" ] },
"system.version" }, actions: [ "insert" ] }
Authentication If copying from a remote server and the remote server has authentication enabled, then you must
include a username, nonce, and key.
The nonce is a one-time password that you request from the remote server using the copydbgetnonce (page 264)
command, as in the following:
use admin
mynonce = db.runCommand( { copydbgetnonce : 1, fromhost: <hostname> } ).nonce
328
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
If running the copydbgetnonce (page 264) command directly on the remote host, you can omit the fromhost
field in the copydbgetnonce (page 264) command.
The key is a hash generated as follows:
hex_md5(mynonce + username + hex_md5(username + ":mongo:" + password))
Replica Sets With read preference configured to set the slaveOk option to true, you may run copydb (page 326)
on a secondary member of a replica set.
Sharded Clusters
• Do not use copydb (page 326) from a mongos (page 601) instance.
• Do not use copydb (page 326) to copy databases that contain sharded collections.
Examples
Copy on the Same Host To copy from the same host, omit the fromhost field.
The following command copies the test database to a new records database on the current mongod (page 583)
instance:
use admin
db.runCommand({
copydb: 1,
fromdb: "test",
todb: "records"
})
Copy from a Remote Host to the Current Host To copy from a remote host, include the fromhost field.
The following command copies the test database from the remote host example.net to a new records database
on the current mongod (page 583) instance:
use admin
db.runCommand({
copydb: 1,
fromdb: "test",
todb: "records",
fromhost: "example.net"
})
Copy Databases from Remote mongod Instances that Enforce Authentication To copy from a remote host that
enforces authentication, include the fromhost, username, nonce and key fields.
The following command copies the test database from a remote host example.net that runs with
authorization to a new records database on the local mongod (page 583) instance. Because the
example.net has authorization enabled, the command includes the username, nonce and key fields:
use admin
db.runCommand({
copydb: 1,
fromdb: "test",
todb: "records",
2.2. Database Commands
329
MongoDB Reference Manual, Release 2.8.0-rc3
fromhost: "example.net",
username: "reportingAdmin",
nonce: "<nonce>",
key: "<passwordhash>"
})
See also:
• db.copyDatabase() (page 102)
• clone (page 320) and db.cloneDatabase() (page 101)
• http://docs.mongodb.org/manual/core/backups and http://docs.mongodb.org/manual/core/impor
createIndexes New in version 2.6.
Definition
createIndexes
Builds one or more indexes on a collection. The createIndexes (page 330) command takes the following
form:
db.runCommand(
{
createIndexes: <collection>,
indexes: [
{
key: {
<key-value_pair>,
<key-value_pair>,
...
},
name: <index_name>,
<option1>,
<option2>,
...
},
{ ... },
{ ... }
]
}
)
The createIndexes (page 330) command takes the following fields:
field string createIndexes The collection for which to create indexes.
field array indexes Specifies the indexes to create. Each document in the array specifies a separate
index.
Each document in the indexes array can take the following fields:
field document key Specifies the index’s fields. For each field, specify a key-value pair in which the
key is the name of the field to index and the value is either the index direction or index type.
If specifying direction, specify 1 for ascending or -1 for descending.
field string name A name that uniquely identifies the index.
field string ns The namespace (i.e. <database>.<collection>) of the collection for which
to create the index. If you omit ns, MongoDB generates the namespace.
330
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
param Boolean background 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 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 Boolean dropDups Creates a unique index on a field that may have duplicates. MongoDB
indexes only the first occurrence of a key and removes all documents from the collection that
contain subsequent occurrences of that key. Specify true to create unique index. The default
value is false.
The option is unavailable for hashed indexes.
Deprecated since version 2.6.
Warning: dropDups will delete data from your collection when building the index.
param Boolean sparse 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 default value is false.
See
http://docs.mongodb.org/manual/core/index-sparse 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 Specifies a value,
in seconds,
as a TTL to
control how long MongoDB retains documents in this collection.
See
http://docs.mongodb.org/manual/tutorial/expire-data for more information on this functionality. This applies only to TTL indexes.
param index version v The index version number. The default index version depends on the version
of mongod (page 583) 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 New in version 2.8.
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.
param document weights For text indexes, a document that contains field and
weight pairs.
The weight is an integer ranging from 1 to 99,999 and denotes 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
http://docs.mongodb.org/manual/tutorial/control-results-of-text-search
to adjust the scores. The default value is 1.
2.2. Database Commands
331
MongoDB Reference Manual, Release 2.8.0-rc3
param string default_language 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
http://docs.mongodb.org/manual/tutorial/specify-language-for-text-index
for more information and examples. The default value is english.
param string language_override For text indexes, the name of the field, in the collection’s 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 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.
param integer 2dsphereIndexVersion For 2dsphere indexes, the 2dsphere 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.
param integer bits 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 For 2d indexes, the lower inclusive boundary for the longitude and latitude
values. The default value is -180.0.
param number max For 2d indexes, the upper inclusive boundary for the longitude and latitude
values. The default value is 180.0.
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.
Considerations An index name, including the namespace, cannot be longer than the Index Name Length (page 693)
limit.
Behavior Non-background indexing operations block all other operations on a database. If you specify multiple
indexes to createIndexes (page 330), MongoDB builds the indexes serially.
If you create an index with one set of options and then issue createIndexes (page 330) with the same index fields
but different options, MongoDB will not change the options nor rebuild the index. To change index options, drop
the existing index with db.collection.dropIndex() (page 29) before running the new createIndexes
(page 330) with the new options.
Example The following command builds two indexes on the inventory collection of the products database:
db.getSiblingDB("products").runCommand(
{
createIndexes: "inventory",
indexes: [
{
key: {
332
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
item: 1,
manufacturer: 1,
model: 1
},
name: "item_manufacturer_model",
unique: true
},
{
key: {
item: 1,
supplier: 1,
model: 1
},
name: "item_supplier_model",
unique: true
}
]
}
)
When the indexes successfully finish building, MongoDB returns a results document that includes a status of "ok"
: 1.
Output The createIndexes (page 330) command returns a document that indicates the success of the operation.
The document contains some but not all of the following fields, depending on outcome:
createIndexes.createdCollectionAutomatically
If true, then the collection didn’t exist and was created in the process of creating the index.
createIndexes.numIndexesBefore
The number of indexes at the start of the command.
createIndexes.numIndexesAfter
The number of indexes at the end of the command.
createIndexes.ok
A value of 1 indicates the indexes are in place. A value of 0 indicates an error.
createIndexes.note
This note is returned if an existing index or indexes already exist. This indicates that the index was not created
or changed.
createIndexes.errmsg
Returns information about any errors.
createIndexes.code
The error code representing the type of error.
create
Definition
create
Explicitly creates a collection. create (page 333) has the following form:
{ create: <collection_name>,
capped: <true|false>,
autoIndexId: <true|false>,
2.2. Database Commands
333
MongoDB Reference Manual, Release 2.8.0-rc3
size: <max_size>,
max: <max_documents>,
flags: <0|1>
}
create (page 333) has the following fields:
field string create The name of the new collection.
field Boolean capped 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 Specify false to disable the automatic creation of an index on the _id
field. Before 2.2, the default value for autoIndexId was false.
field integer size The maximum size for the capped collection. Once a capped collection reaches
its maximum size, MongoDB overwrites older old documents with new documents. The size
field is required for capped collections.
field integer max The maximum number of documents to keep in the capped collection. The size
limit takes precedence over this limit. If a capped collection reaches its maximum size before it
reaches the maximum number of documents, MongoDB removes old documents. If you use this
limit, ensure that the size limit is sufficient to contain the documents limit.
field integer flags New in version 2.6.
Set to 0 to disable the usePowerOf2Sizes (page 322) allocation strategy for this collection, or 1 to enable usePowerOf2Sizes (page 322). Defaults to 1 unless the
newCollectionsUsePowerOf2Sizes parameter is set to false.
For more information on the autoIndexId field in versions before 2.2, see _id Fields and Indexes on Capped
Collections (page 797).
The db.createCollection() (page 104) method wraps the create (page 333) command.
Considerations The create (page 333) command obtains a write lock on the affected database and will block
other operations until it has completed. The write lock for this operation is typically short lived. However, allocations
for large capped collections may take longer.
Example To create a capped collection limited to 64 kilobytes, issue the command in the following form:
db.runCommand( { create: "collection", capped: true, size: 64 * 1024 } )
dropDatabase
dropDatabase
The dropDatabase (page 334) command drops the current database, deleting the associated data files.
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 266) command in the database you are
deleting.
To run this command, issue the use <database> command in the shell, replacing <database> with the
name of the database you wish to delete. Then use the following command form:
{ dropDatabase: 1 }
The mongo (page 610) shell also provides the following equivalent helper method db.dropDatabase()
(page 111).
334
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Warning: This command obtains a global write lock and will block other operations until it has completed.
See also:
dropAllUsersFromDatabase (page 266)
dropIndexes
dropIndexes
The dropIndexes (page 335) command drops one or all indexes from the current collection. To drop all
indexes, issue the command like so:
{ dropIndexes: "collection", index: "*" }
To drop a single, issue the command by specifying the name of the index you want to drop. For example, to
drop the index named age_1, use the following command:
{ dropIndexes: "collection", index: "age_1" }
The shell provides a useful command helper. Here’s the equivalent command:
db.collection.dropIndex("age_1");
Warning: This command obtains a write lock on the affected database and will block other operations until
it has completed.
drop
drop
The drop (page 335) command removes an entire collection from a database. The command has following
syntax:
{ drop: <collection_name> }
The mongo (page 610) shell provides the equivalent helper method db.collection.drop() (page 28).
This command also removes any indexes associated with the dropped collection.
Warning: This command obtains a write lock on the affected database and will block other operations until
it has completed.
filemd5
filemd5
The filemd5 (page 335) command returns the md5 hashes for a single file stored using the GridFS specification. Client libraries use this command to verify that files are correctly written to MongoDB. The command
takes the files_id of the file in question and the name of the GridFS root collection as arguments. For
example:
{ filemd5: ObjectId("4f1f10e37671b50e4ecd2776"), root: "fs" }
MongoDB computes the filemd5 using all data in the GridFS file object pulled sequentially from each chunk
in the chunks collection.
fsync
2.2. Database Commands
335
MongoDB Reference Manual, Release 2.8.0-rc3
Definition
fsync
Forces the mongod (page 583) process to flush all pending writes from the storage layer to disk. Optionally,
you can use fsync (page 336) to lock the mongod (page 583) instance and block write operations for the
purpose of capturing backups.
As applications write data, MongoDB records the data in the storage layer and then writes the data to disk within
the syncPeriodSecs interval, which is 60 seconds by default. Run fsync (page 336) when you want to
flush writes to disk ahead of that interval.
The fsync (page 336) command has the following syntax:
{ fsync: 1, async: <Boolean>, lock: <Boolean> }
The fsync (page 336) command has the following fields:
field integer fsync Enter “1” to apply fsync (page 336).
field Boolean async Runs fsync (page 336) asynchronously. By default, the fsync (page 336)
operation is synchronous.
field Boolean lock Locks mongod (page 583) instance and blocks all write operations.
Behavior An fsync (page 336) lock is only possible on individual mongod (page 583) instances
of a sharded cluster, not on the entire cluster.
To backup an entire sharded cluster, please see
http://docs.mongodb.org/manual/administration/backup-sharded-clusters for more information.
If your mongod (page 583) has journaling enabled, consider using another method to create a back up of the data set.
After fsync (page 336), with lock, runs on a mongod (page 583), all write operations will block until a subsequent
unlock. Read operations may also block. As a result, fsync (page 336), with lock, is not a reliable mechanism for
making a mongod (page 583) instance operate in a read-only mode.
Important: Blocked read operations prevent verification of authentication. Such reads are necessary to establish new
connections to a mongod (page 583) that enforces authorization checks.
Warning: When calling fsync (page 336) with lock, ensure that the connection remains open to allow a subsequent call to db.fsyncUnlock() (page 114).
Closing the connection may make it difficult to release the lock.
Examples
Run Asynchronously The fsync (page 336) operation is synchronous by default To run fsync (page 336) asynchronously, use the async field set to true:
{ fsync: 1, async: true }
The operation returns immediately. To view the status of the fsync (page 336) operation, check the output of
db.currentOp() (page 105).
Lock mongod Instance The primary use of fsync (page 336) is to lock the mongod (page 583) instance in order
to back up the files withing mongod (page 583)�s dbPath. The operation flushes all data to the storage layer and
blocks all write operations until you unlock the mongod (page 583) instance.
336
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
To lock the database, use the lock field set to true:
{ fsync: 1, lock: true }
You may continue to perform read operations on a mongod (page 583) instance that has a fsync (page 336) lock.
However, after the first write operation all subsequent read operations wait until you unlock the mongod (page 583)
instance.
Unlock mongod Instance To unlock the mongod (page 583), use db.fsyncUnlock() (page 114):
db.fsyncUnlock();
Check Lock Status To check the state of the fsync lock, use db.currentOp() (page 105). Use the following
JavaScript function in the shell to test if mongod (page 583) instance is currently locked:
serverIsLocked = function () {
var co = db.currentOp();
if (co && co.fsyncLock) {
return true;
}
return false;
}
After loading this function into your mongo (page 610) shell session call it, with the following syntax:
serverIsLocked()
This function will return true if the mongod (page 583) instance is currently locked and false if the mongod
(page 583) is not locked.
getParameter
getParameter
getParameter (page 337) is an administrative command for retrieving the value of options normally set on
the command line. Issue commands against the admin database as follows:
{ getParameter: 1, <option>: 1 }
The values specified for getParameter and <option> do not affect the output. The command works with
the following options:
•quiet
•notablescan
•logLevel
•syncdelay
See also:
setParameter (page 343) for more about these parameters.
listCollections New in version 2.8.0.
2.2. Database Commands
337
MongoDB Reference Manual, Release 2.8.0-rc3
Definition
listCollections
Returns an array with a document for each collection in the database.
field document filter A query expression that filters the contents of the collections (page 338)
array in the listCollections (page 338) result document.
Output
listCollections.collections
An array of documents for each collection.
listCollections.collections[n].name
The name of the collection.
listCollections.collections[n].options
A document with a mapping of collection options and their values.
listCollections.ok
The return value for the command. A value of 1 indicates success.
Examples
List All Collections To return all collections in the records database use the following operation in the mongo
(page 610) shell:
use records
db.runCommand( { listCollections: 1 } );
Consider the following output for a database that only has a users collection:
{
"collections" : [
{
"name" : "users",
"options" : {
"flags" : 1
}
}
],
"ok" : 1
}
List Matching Collections Use the filter argument to the listCollections (page 338) command to specify
a query that will limit the collections returned in the list, as in the following examples:
use records
db.runCommand( { listCollections: 1, filter: { capped: true } } );
db.runCommand( { listCollections: 1, filter: { name: { $regex: "^users\..*" } } } );
listIndexes New in version 2.8.0.
Definition
338
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
listIndexes
Returns information about the indexes on the specified collection. The indexes (page 339) field contains an
array with documents for every index that displays important information about the index’s definition. Consider
the following command document:
{ "listIndexes": "<collection-name>" }
field string collection The name of the collection.
Output
listIndexes.indexes
listIndexes.indexes[n].v
The index version.
listIndexes.indexes[n].key
A document that contains the index specification.
listIndexes.indexes[n].name
The name of the index.
listIndexes.indexes[n].ns
The namespace of the collection where the index exists.
listIndexes.indexes[n].background
A boolean that is true when the index is built in the background. Only appears in indexes (page 339) when
true.
listIndexes.indexes[n].sparse
A boolean that is true when the index has a sparse filter. Only appears in indexes (page 339) when true.
listIndexes.indexes[n].unique
A boolean that is true when the index has a unique constraint. Only appears in indexes (page 339) when
true.
listIndexes.indexes[n].expireAfterSeconds
The number of seconds. See http://docs.mongodb.org/manual/tutorial/expire-data for
more information about data expiration. Only appears for indexes with that expire data.
listIndexes.indexes[n].bucketSize
The size of the buckets for geoHaystack indexes. See http://docs.mongodb.org/manual/core/geohaystack
for more information. Only appears for geoHaystack indexes.
listIndexes.ok
The return value for the command. A value of 1 indicates success.
logRotate
logRotate
The logRotate (page 339) command is an administrative command that allows you to rotate the MongoDB logs to prevent a single logfile from consuming too much disk space. You must issue the logRotate
(page 339) command against the admin database in the form:
{ logRotate: 1 }
Note: Your mongod (page 583) instance needs to be running with the --logpath [file] option.
You may also rotate the logs by sending a SIGUSR1 signal to the mongod (page 583) process. If your mongod
(page 583) has a process ID of 2200, here’s how to send the signal on Linux:
2.2. Database Commands
339
MongoDB Reference Manual, Release 2.8.0-rc3
kill -SIGUSR1 2200
logRotate (page 339) renames the existing log file by appending the current timestamp to the filename. The
appended timestamp has the following form:
<YYYY>-<mm>-<DD>T<HH>-<MM>-<SS>
Then logRotate (page 339) creates a new log file with the same name as originally specified by the
systemLog.path setting to mongod (page 583) or mongos (page 601).
Note: New in version 2.0.3: The logRotate (page 339) command is available to mongod (page 583)
instances running on Windows systems with MongoDB release 2.0.3 and higher.
reIndex
reIndex
The reIndex (page 340) command 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. Use the following
syntax:
{ reIndex: "collection" }
Normally, MongoDB compacts indexes during routine updates. For most users, the reIndex (page 340)
command 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.
Call reIndex (page 340) using the following form:
db.collection.reIndex();
Note: For replica sets, reIndex (page 340) will not propagate from the primary to secondaries. reIndex
(page 340) will only affect a single mongod (page 583) instance.
Important: reIndex (page 340) will rebuild indexes in the background if the index was originally specified
with this option. However, reIndex (page 340) will rebuild the _id index in the foreground, which takes the
database’s write lock.
See
http://docs.mongodb.org/manual/core/index-creation for more information on the behavior of
indexing operations in MongoDB.
renameCollection
Definition
renameCollection
Changes the name of an existing collection. Specify collections to renameCollection (page 340) in the
form of a complete namespace, which includes the database name. Issue the renameCollection (page 340)
command against the admin database. The command takes the following form:
{ renameCollection: "<source_namespace>", to: "<target_namespace>", dropTarget: <true|false> }
The command contains the following fields:
340
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
field string renameCollection The namespace of the collection to rename. The namespace is a
combination of the database name and the name of the collection.
field string to The new namespace of the collection. If the new namespace specifies a different
database, the renameCollection (page 340) command copies the collection to the new
database and drops the source collection.
field boolean dropTarget If true, mongod (page 583) will drop the target of
renameCollection (page 340) prior to renaming the collection.
renameCollection (page 340) is suitable for production environments; however:
•renameCollection (page 340) blocks all database activity for the duration of the operation.
•renameCollection (page 340) is not compatible with sharded collections.
Warning: renameCollection (page 340) fails if target is the name of an existing collection and
you do not specify dropTarget: true.
If the renameCollection (page 340) operation does not complete the target collection and indexes
will not be usable and will require manual intervention to clean up.
Exceptions
exception 10026 Raised if the source namespace does not exist.
exception 10027 Raised if the target namespace exists and dropTarget is either false or unspecified.
exception 15967 Raised if the target namespace is an invalid collection name.
Shell Helper The shell helper db.collection.renameCollection() (page 69) provides a simpler interface to using this command within a database. The following is equivalent to the previous example:
db.source-namespace.renameCollection( "target" )
Warning: You cannot use renameCollection (page 340) with sharded collections.
Warning: This command obtains a global write lock and will block other operations until it has completed.
repairCursor New in version 2.8.0.
repairCursor
Returns a cursor that iterates through all documents in a collection, omitting those that are not valid BSON.
Used by mongodump (page 622) to provide the underlying functionality for the --repair option.
For internal use.
repairDatabase
Definition
repairDatabase
Checks and repairs errors and inconsistencies in data storage. repairDatabase (page 341) is analogous to
a fsck command for file systems. Run the repairDatabase (page 341) command to ensure data integrity
after the system experiences an unexpected system restart or crash, if:
2.2. Database Commands
341
MongoDB Reference Manual, Release 2.8.0-rc3
1.The mongod (page 583) instance is not running with journaling enabled.
When using journaling, there is almost never any need to run repairDatabase (page 341). In the event
of an unclean shutdown, the server will be able to restore the data files to a pristine state automatically.
2.There are no other intact replica set members with a complete data set.
Warning:
During normal operations, only use the repairDatabase (page 341) command
and wrappers including db.repairDatabase() (page 123) in the mongo (page 610) shell and
mongod --repair, to compact database files and/or reclaim disk space. Be aware that these operations remove and do not save any 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 341).
repairDatabase (page 341) takes the following form:
{ repairDatabase: 1 }
repairDatabase (page 341) has the following fields:
field boolean preserveClonedFilesOnFailure When true, repairDatabase will not delete
temporary files in the backup directory on error, and all new files are created with the “backup”
instead of “_tmp” directory prefix. By default repairDatabase does not delete temporary
files, and uses the “_tmp” naming prefix for new files.
field boolean backupOriginalFiles When true, repairDatabase moves old database files to
the backup directory instead of deleting them before moving new files into place. New files are
created with the “backup” instead of “_tmp” directory prefix. By default, repairDatabase
leaves temporary files unchanged, and uses the “_tmp” naming prefix for new files.
You can explicitly set the options as follows:
{ repairDatabase: 1,
preserveClonedFilesOnFailure: <boolean>,
backupOriginalFiles: <boolean> }
Warning: This command obtains a global write lock and will block other operations until it has completed.
Note: repairDatabase (page 341) requires free disk space equal to the size of your current data set plus
2 gigabytes. If the volume that holds dbpath lacks sufficient space, you can mount a separate volume and
use that for the repair. When mounting a separate volume for repairDatabase (page 341) you must run
repairDatabase (page 341) from the command line and use the --repairpath switch to specify the
folder in which to store temporary repair files.
See mongod --repair and mongodump --repair for information on these related options.
Behavior Changed in version 2.6: The repairDatabase (page 341) command is now available for secondary as
well as primary members of replica sets.
The repairDatabase (page 341) command compacts all collections in the database. It is identical to running the
compact (page 322) command on each collection individually.
repairDatabase (page 341) reduces the total size of the data files on disk. It also recreates all indexes in the
database.
The time requirement for repairDatabase (page 341) depends on the size of the data set.
342
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
You may invoke repairDatabase (page 341) from multiple contexts:
• Use the mongo (page 610) shell to run the command, as above.
• Use the db.repairDatabase() (page 123) in the mongo (page 610) shell.
• Run mongod (page 583) directly from your system’s shell. Make sure that mongod (page 583) isn’t already
running, and that you invoke mongod (page 583) as a user that has access to MongoDB’s data files. Run as:
mongod --repair
To add a repair path:
mongod --repair --repairpath /opt/vol2/data
See repairPath for more information.
Note: mongod --repair will fail if your database is not a master or primary. In most cases, you should
recover a corrupt secondary using the data from an existing intact node. To run repair on a secondary/slave
restart the instance in standalone mode without the --replSet or --slave options.
Example
{ repairDatabase: 1 }
Using repairDatabase to Reclaim Disk Space You should not use repairDatabase (page 341) for data
recovery unless you have no other option.
However, if you trust that there is no corruption and you have enough free space, then repairDatabase (page 341)
is the appropriate and the only way to reclaim disk space.
setParameter
setParameter
setParameter (page 343) is an administrative command for modifying options normally set on the command
line. You must issue the setParameter (page 343) command against the admin database in the form:
{ setParameter: 1, <option>: <value> }
Replace the <option> with one of the supported setParameter (page 343) options:
•journalCommitInterval
•logLevel
•logUserIds
•notablescan
•quiet
•replApplyBatchSize
•replIndexPrefetch
•syncdelay
•traceExceptions
•textSearchEnabled
•sslMode
2.2. Database Commands
343
MongoDB Reference Manual, Release 2.8.0-rc3
•clusterAuthMode
•userCacheInvalidationIntervalSecs
•wiredTigerEngineRuntimeConfigSetting
•logComponentVerbosity
shutdown
shutdown
The shutdown (page 344) command cleans up all database resources and then terminates the process. You
must issue the shutdown (page 344) command against the admin database in the form:
{ shutdown: 1 }
Note: Run the shutdown (page 344) against the admin database. When using shutdown (page 344), the
connection must originate from localhost or use an authenticated connection.
If the node you’re trying to shut down is a replica set primary, then the command will succeed only if there
exists a secondary node whose oplog data is within 10 seconds of the primary. You can override this protection
using the force option:
{ shutdown: 1, force: true }
Alternatively, the shutdown (page 344) command also supports a timeoutSecs argument which allows
you to specify a number of seconds to wait for other members of the replica set to catch up:
{ shutdown: 1, timeoutSecs: 60 }
The equivalent mongo (page 610) shell helper syntax looks like this:
db.shutdownServer({timeoutSecs: 60});
touch
touch
New in version 2.2.
The touch (page 344) command loads data from the data storage layer into memory. touch (page 344) can
load the data (i.e. documents) indexes or both documents and indexes. Use this command to ensure that a
collection, and/or its indexes, are in memory before another operation. By loading the collection or indexes
into memory, mongod (page 583) will ideally be able to perform subsequent operations more efficiently. The
touch (page 344) command has the following prototypical form:
{ touch: [collection], data: [boolean], index: [boolean] }
By default, data and index are false, and touch (page 344) will perform no operation. For example, to load
both the data and the index for a collection named records, you would use the following command in the
mongo (page 610) shell:
db.runCommand({ touch: "records", data: true, index: true })
touch (page 344) will not block read and write operations on a mongod (page 583), and can run on secondary
members of replica sets.
Considerations
344
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Performance Impact Using touch (page 344) to control or tweak what a mongod (page 583) stores in memory
may displace other records data in memory and hinder performance. Use with caution in production systems.
Replication and Secondaries If you run touch (page 344) on a secondary, the secondary will enter a
RECOVERING state to prevent clients from sending read operations during the touch (page 344) operation. When
touch (page 344) finishes the secondary will automatically return to SECONDARY state. See state (page 298) for
more information on replica set member states.
Storage Engines Changed in version 2.8.0.
If the current storage engine does not support touch (page 344), the touch (page 344) command will return an
error.
The mmapv1 storage engine supports touch (page 344).
The wiredTiger storage engine does not support touch (page 344).
2.2. Database Commands
345
MongoDB Reference Manual, Release 2.8.0-rc3
Diagnostic Commands
Diagnostic Commands
Name
Description
availableQueryOptions Internal command that reports on the capabilities of the current MongoDB
(page 346)
instance.
buildInfo (page 346)
Displays statistics about the MongoDB build.
collStats (page 348)
Reports storage utilization statics for a specified collection.
connPoolStats
Reports statistics on the outgoing connections from this MongoDB instance to
(page 350)
other MongoDB instances in the deployment.
cursorInfo (page 352)
Deprecated. Reports statistics on active cursors.
dataSize (page 352)
Returns the data size for a range of data. For internal use.
dbHash (page 352)
Internal command to support sharding.
dbStats (page 352)
Reports storage utilization statistics for the specified database.
diagLogging (page 354) Provides a diagnostic logging. For internal use.
driverOIDTest
Internal command that converts an ObjectId to a string to support tests.
(page 354)
explain (page 354)
Returns information on the execution of various operations.
features (page 356)
Reports on features available in the current MongoDB instance.
getCmdLineOpts
Returns a document with the run-time arguments to the MongoDB instance and
(page 357)
their parsed options.
getLog (page 357)
Returns recent log messages.
hostInfo (page 358)
Returns data that reflects the underlying host system.
indexStats (page 360)
Experimental command that collects and aggregates statistics on all indexes.
isSelf
Internal command to support testing.
listCommands
Lists all database commands provided by the current mongod (page 583) instance.
(page 365)
listDatabases
Returns a document that lists all databases and returns basic database statistics.
(page 365)
netstat (page 365)
Internal command that reports on intra-deployment connectivity. Only available
for mongos (page 601) instances.
ping (page 365)
Internal command that tests intra-deployment connectivity.
profile (page 366)
Interface for the database profiler.
serverStatus
Returns a collection metrics on instance-wide resource utilization and status.
(page 366)
shardConnPoolStats
Reports statistics on a mongos (page 601)�s connection pool for client operations
(page 386)
against shards.
top (page 387)
Returns raw usage statistics for each database in the mongod (page 583) instance.
validate (page 389)
Internal command that scans for a collection’s data and indexes for correctness.
whatsmyuri (page 392)
Internal command that returns information on the current client.
availableQueryOptions
availableQueryOptions
availableQueryOptions (page 346) is an internal command that is only available on mongos (page 601)
instances.
buildInfo
buildInfo
The buildInfo (page 346) command is an administrative command which returns a build summary for the
current mongod (page 583). buildInfo (page 346) has the following prototype form:
346
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
{ buildInfo: 1 }
In the mongo (page 610) shell, call buildInfo (page 346) in the following form:
db.runCommand( { buildInfo: 1 } )
Example
The output document of buildInfo (page 346) has the following form:
{
"version" : "<string>",
"gitVersion" : "<string>",
"sysInfo" : "<string>",
"loaderFlags" : "<string>",
"compilerFlags" : "<string>",
"allocator" : "<string>",
"versionArray" : [ <num>, <num>, <...> ],
"javascriptEngine" : "<string>",
"bits" : <num>,
"debug" : <boolean>,
"maxBsonObjectSize" : <num>,
"ok" : <num>
}
Consider the following documentation of the output of buildInfo (page 346):
buildInfo
The document returned by the buildInfo (page 346) command.
buildInfo.gitVersion
The commit identifier that identifies the state of the code used to build the mongod (page 583).
buildInfo.sysInfo
A string that holds information about the operating system, hostname, kernel, date, and Boost version used
to compile the mongod (page 583).
buildInfo.loaderFlags
The flags passed to the loader that loads the mongod (page 583).
buildInfo.compilerFlags
The flags passed to the compiler that builds the mongod (page 583) binary.
buildInfo.allocator
Changed in version 2.2.
The memory allocator that mongod (page 583) uses. By default this is tcmalloc after version 2.2, and
system before 2.2.
buildInfo.versionArray
An array that conveys version information about the mongod (page 583) instance. See version for a
more readable version of this string.
buildInfo.javascriptEngine
Changed in version 2.4.
A string that reports the JavaScript engine used in the mongod (page 583) instance. By default, this is V8
after version 2.4, and SpiderMonkey before 2.4.
buildInfo.bits
A number that reflects the target processor architecture of the mongod (page 583) binary.
2.2. Database Commands
347
MongoDB Reference Manual, Release 2.8.0-rc3
buildInfo.debug
A boolean. true when built with debugging options.
buildInfo.maxBsonObjectSize
A number that reports the Maximum BSON Document Size (page 692).
collStats
Definition
collStats
The collStats (page 348) command returns a variety of storage statistics for a given collection. Use the
following syntax:
{ collStats: "collection" , scale : 1024, verbose: true }
Specify the collection you want statistics for, and use the scale argument to scale the output: a value
of 1024 renders the results in kilobytes. The verbose: true option increases reporting for the mmapv1
storage engine.
Examine the following example output, which uses the db.collection.stats() (page 71) helper in the
mongo (page 610) shell.
> db.users.stats()
{
"ns" : "app.users",
"count" : 9,
"size" : 432,
"avgObjSize" : 48,
"storageSize" : 3840,
"nindexes" : 2,
"totalIndexSize" : 16384,
"indexSizes" : {
"_id_" : 8192,
"username" : 8192
},
// ...
"ok" : 1
}
//
//
//
//
//
//
//
//
namespace
number of documents
collection size in bytes
average object size in bytes
(pre)allocated space for the collection in bytes
number of indexes
total index size in bytes
size of specific indexes in bytes
Note: The scale factor rounds values to whole numbers. This can produce unexpected results in some situations.
If collStats (page 348) operates on a capped collection, then the following fields will also be present:
> db.users.stats()
{
// ...
"capped" : true,
"max" : NumberLong("9223372036854775807"),
"ok" : 1
}
Output
collStats.ns
The namespace of the current collection, which follows the format [database].[collection].
collStats.count
The number of objects or documents in this collection.
348
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
collStats.size
The total size of all records in a collection. This value does not include the record header, which is 16 bytes per
record, but does include the record’s padding. Additionally size (page 349) does not include the size of any
indexes associated with the collection, which the totalIndexSize (page 349) field reports.
The scale argument affects this value.
collStats.avgObjSize
The average size of an object in the collection. The scale argument affects this value.
collStats.storageSize
The total amount of storage allocated to this collection for document storage. The scale argument affects this
value.
For mmapv1, storageSize (page 349) will not decrease as you remove or shrink documents.
collStats.numExtents
The total number of contiguously allocated data file regions. Only present when using the mmapv1 storage
engine.
collStats.nindexes
The number of indexes on the collection. All collections have at least one index on the _id field.
Changed in version 2.2: Before 2.2, capped collections did not necessarily have an index on the _id field, and
some capped collections created with pre-2.2 versions of mongod (page 583) may not have an _id index.
collStats.lastExtentSize
The size of the last extent allocated. The scale argument affects this value. Only present when using the
mmapv1 storage engine.
collStats.paddingFactor
Deprecated since version 2.8.0: paddingFactor (page 349) is no longer used in 2.8.0, and remains hard
coded to 1.0 for compatibility only.
Changed in version 2.8.0: paddingFactor (page 349) only appears when using the mmapv1 storage engine.
The amount of additional space added to the end of each document at insert time.
paddingFactor (page 349) by the size of the document to determine record size.
Multiply the
collStats.userFlags
Changed in version 2.8.0: userFlags (page 349) only appears when using the mmapv1 storage engine.
New in version 2.2.
Reports the flags on this collection set by the user. In version 2.2 the only user flag is usePowerOf2Sizes
(page 322). If usePowerOf2Sizes (page 322) is enabled, userFlags (page 349) will be set to 1, otherwise
it will be 0.
See the collMod (page 321) command for more information on setting user flags and usePowerOf2Sizes
(page 322).
collStats.totalIndexSize
The total size of all indexes. The scale argument affects this value.
collStats.indexSizes
This field specifies the key and size of every existing index on the collection. The scale argument affects this
value.
collStats.capped
This field will be “true” if the collection is capped.
collStats.max
Shows the maximum number of documents that may be present in a capped collection.
2.2. Database Commands
349
MongoDB Reference Manual, Release 2.8.0-rc3
collStats.maxSize
Shows the maximum size of a capped collection.
collStats.wiredtiger
New in version 2.8.0.
wiredtiger (page 350) only appears when using the wiredTiger storage engine and contains data reported
directly by the WiredTiger engine.
connPoolStats
Definition
connPoolStats
The command connPoolStats (page 350) returns information regarding the number of open connections to
the current database instance, including client connections and server-to-server connections for replication and
clustering.
Note: connPoolStats (page 350) only returns meaningful results for mongos (page 601) instances and
for mongod (page 583) instances in sharded clusters.
The command takes the following form:
{ connPoolStats: 1 }
The value of the argument (i.e. 1 ) does not affect the output of the command.
Output
connPoolStats.hosts
The sub-documents of the hosts (page 350) document report connections between the mongos (page 601) or
mongod (page 583) instance and each component mongod (page 583) of the sharded cluster.
connPoolStats.hosts.[host].available
available (page 350) reports the total number of connections that the mongos (page 601) or mongod
(page 583) could use to connect to this mongod (page 583).
connPoolStats.hosts.[host].created
created (page 350) reports the number of connections that this mongos (page 601) or mongod
(page 583) has ever created for this host.
connPoolStats.replicaSets
replicaSets (page 350) is a document that contains replica set information for the sharded cluster.
connPoolStats.replicaSets.shard
The shard (page 350) document reports on each shard within the sharded cluster
connPoolStats.replicaSets.[shard].host
The host (page 350) field holds an array of document that reports on each host within the shard in the
replica set.
These values derive from the replica set status (page 296) values.
connPoolStats.replicaSets.[shard].host[n].addr
addr (page 350) reports the address for the host in the sharded cluster in the format of
“[hostname]:[port]”.
connPoolStats.replicaSets.[shard].host[n].ok
ok (page 350) reports false when:
•the mongos (page 601) or mongod (page 583) cannot connect to instance.
350
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
•the mongos (page 601) or mongod (page 583) received a connection exception or error.
This field is for internal use.
connPoolStats.replicaSets.[shard].host[n].ismaster
ismaster (page 351) reports true if this host (page 350) is the primary member of the replica
set.
connPoolStats.replicaSets.[shard].host[n].hidden
hidden (page 351) reports true if this host (page 350) is a hidden member of the replica set.
connPoolStats.replicaSets.[shard].host[n].secondary
secondary (page 351) reports true if this host (page 350) is a secondary member of the replica
set.
connPoolStats.replicaSets.[shard].host[n].pingTimeMillis
pingTimeMillis (page 351) reports the ping time in milliseconds from the mongos (page 601)
or mongod (page 583) to this host (page 350).
connPoolStats.replicaSets.[shard].host[n].tags
New in version 2.2.
tags (page 351) reports the tags, if this member of the set has tags configured.
connPoolStats.replicaSets.[shard].master
master (page 351) reports the ordinal identifier of the host in the host (page 350) array that is the
primary of the replica set.
connPoolStats.replicaSets.[shard].nextSlave
Deprecated since version 2.2.
nextSlave (page 351) reports the secondary member that the mongos (page 601) will use to service
the next request for this replica set.
connPoolStats.createdByType
createdByType (page 351) document reports the number of each type of connection that mongos (page 601)
or mongod (page 583) has created in all connection pools.
mongos (page 601) connect to mongod (page 583) instances using one of three types of connections. The
following sub-document reports the total number of connections by type.
connPoolStats.createdByType.master
master (page 351) reports the total number of connections to the primary member in each cluster.
connPoolStats.createdByType.set
set (page 351) reports the total number of connections to a replica set member.
connPoolStats.createdByType.sync
sync (page 351) reports the total number of config database connections.
connPoolStats.totalAvailable
totalAvailable (page 351) reports the running total of connections from the mongos (page 601) or
mongod (page 583) to all mongod (page 583) instances in the sharded cluster available for use.
connPoolStats.totalCreated
totalCreated (page 351) reports the total number of connections ever created from the mongos (page 601)
or mongod (page 583) to all mongod (page 583) instances in the sharded cluster.
connPoolStats.numDBClientConnection
numDBClientConnection (page 351) reports the total number of connections from the mongos (page 601)
or mongod (page 583) to all of the mongod (page 583) instances in the sharded cluster.
connPoolStats.numAScopedConnection
numAScopedConnection (page 351) reports the number of exception safe connections created from
2.2. Database Commands
351
MongoDB Reference Manual, Release 2.8.0-rc3
mongos (page 601) or mongod (page 583) to all mongod (page 583) in the sharded cluster. The mongos
(page 601) or mongod (page 583) releases these connections after receiving a socket exception from the
mongod (page 583).
cursorInfo Deprecated since version 2.6: Use the serverStatus (page 366) command to return the
serverStatus.metrics.cursor (page 385) information instead.
cursorInfo
The cursorInfo (page 352) command returns information about current cursor allotment and use. Use the
following form:
{ cursorInfo: 1 }
The value (e.g. 1 above) does not affect the output of the command.
cursorInfo (page 352) returns the total number of open cursors (totalOpen), the size of client cursors
in current use (clientCursors_size), and the number of timed out cursors since the last server restart
(timedOut).
dataSize
dataSize
The dataSize (page 352) command returns the data size for a set of data within a certain range:
{ dataSize: "database.collection", keyPattern: { field: 1 }, min: { field: 10 }, max: { field: 1
This will return a document that contains the size of all matching documents.
Replace
database.collection value with database and collection from your deployment. The keyPattern,
min, and max parameters are options.
The amount of time required to return dataSize (page 352) depends on the amount of data in the collection.
dbHash
dbHash
dbHash (page 352) is a command that supports config servers and is not part of the stable client facing API.
dbStats
Definition
dbStats
The dbStats (page 352) command returns storage statistics for a given database. The command takes the
following syntax:
{ dbStats: 1, scale: 1 }
The values of the options above do not affect the output of the command. The scale option allows you to
specify how to scale byte values. For example, a scale value of 1024 will display the results in kilobytes
rather than in bytes:
{ dbStats: 1, scale: 1024 }
Note: Because scaling rounds values to whole numbers, scaling may return unlikely or unexpected results.
The time required to run the command depends on the total size of the database. Because the command must
touch all data files, the command may take several seconds to run.
352
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
In the mongo (page 610) shell, the db.stats() (page 126) function provides a wrapper around dbStats
(page 352).
Output
dbStats.db
Contains the name of the database.
dbStats.collections
Contains a count of the number of collections in that database.
dbStats.objects
Contains a count of the number of objects (i.e. documents) in the database across all collections.
dbStats.avgObjSize
The average size of each document in bytes. This is the dataSize (page 353) divided by the number of
documents.
dbStats.dataSize
The total size in bytes of the data held in this database including the padding factor. The scale argument
affects this value. The dataSize (page 353) will not decrease when documents shrink, but will decrease when
you remove documents.
dbStats.storageSize
The total amount of space in bytes allocated to collections in this database for document storage. The scale
argument affects this value. The storageSize (page 353) does not decrease as you remove or shrink documents.
dbStats.numExtents
Contains a count of the number of extents in the database across all collections.
dbStats.indexes
Contains a count of the total number of indexes across all collections in the database.
dbStats.indexSize
The total size in bytes of all indexes created on this database. The scale arguments affects this value.
dbStats.fileSize
The total size in bytes of the data files that hold the database. This value includes preallocated space and the
padding factor. The value of fileSize (page 353) only reflects the size of the data files for the database and
not the namespace file.
The scale argument affects this value. Only present when using the mmapv1 storage engine.
dbStats.nsSizeMB
The total size of the namespace files (i.e. that end with .ns) for this database. You cannot change the size of
the namespace file after creating a database, but you can change the default size for all new namespace files with
the nsSize runtime option.
Only present when using the mmapv1 storage engine.
See also:
The nsSize option, and Maximum Namespace File Size (page 692)
dbStats.dataFileVersion
New in version 2.4.
Document that contains information about the on-disk format of the data files for the database. Only present
when using the mmapv1 storage engine.
dbStats.dataFileVersion.major
New in version 2.4.
2.2. Database Commands
353
MongoDB Reference Manual, Release 2.8.0-rc3
The major version number for the on-disk format of the data files for the database. Only present when using the
mmapv1 storage engine.
dbStats.dataFileVersion.minor
New in version 2.4.
The minor version number for the on-disk format of the data files for the database. Only present when using the
mmapv1 storage engine.
dbStats.extentFreeList
New in version 2.8.0.
dbStats.extentFreeList.num
New in version 2.8.0.
Number of extents in the freelist. Only present when using the mmapv1 storage engine.
dbStats.extentFreeList.size
New in version 2.8.0.
Total size of the extents on the freelist.
The scale argument affects this value. Only present when using the mmapv1 storage engine.
diagLogging Deprecated since version 2.8.0.
diagLogging
diagLogging (page 354) is a command that captures additional data for diagnostic purposes and is not part
of the stable client facing API.
diaglogging obtains a write lock on the affected database and will block other operations until it completes.
driverOIDTest
driverOIDTest
driverOIDTest (page 354) is an internal command.
explain
Definition
explain
New in version 2.8.
The explain (page 354) command provides information on the execution of the following commands: count
(page 213), group (page 216), delete (page 234), and update (page 251).
Although MongoDB provides the explain (page 354) command, the preferred method for running explain
(page 354) is to use the db.collection.explain() (page 33) helper.
Note: The shell helpers(), db.collection.explain() (page 33) and cursor.explain() (page 85),
are the only available mechanisms for explaining db.collection.find() (page 36) operations.
The explain (page 354) command has the following syntax:
{
explain: <command>,
verbosity: <string>
}
354
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
The command takes the following fields:
field document explain A document specifying the command for which to return the execution information. For details on the specific command document, see count (page 213), group
(page 216), delete (page 234), and update (page 251).
For find() operations, see db.collection.explain() (page 33).
field string verbosity A string specifying the mode in which to run explain (page 354). The
mode affects the behavior of explain (page 354) and determines the amount of information
to return.
Possible modes are: “queryPlanner” (page 355), “executionStats” (page 355), and “allPlansExecution” (page 355). For more information on the modes, see explain behavior (page 355).
By default, explain (page 354) runs in “allPlansExecution” (page 355) mode.
Behavior The behavior of explain (page 354) and the amount of information returned depend on the verbosity
mode.
queryPlanner Mode MongoDB runs the query optimizer to choose the winning plan for the operation
under evaluation. explain (page 354) returns the queryPlanner information for the evaluated <command>.
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, explain (page 354) returns information about the update or delete operations that would be
performed, but does not apply the modifications to the database.
explain (page 354) returns the queryPlanner and executionStats information for the evaluated
<command>. However, executionStats does not provide query execution information for the rejected plans.
allPlansExecution Mode By default, explain (page 354) runs in "allPlansExecution" verbosity
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, explain (page 354) returns information about the update or delete operations that would be
performed, but does not apply the modifications to the database.
explain (page 354) returns the queryPlanner and executionStats information for the evaluated
<command>. The executionStats includes the completed query execution information for the winning plan.
If the query optimizer considered more than one plan, executionStats information also includes the partial
execution information captured during the plan selection phase for both the winning and rejected candidate plans.
Examples
queryPlanner Mode The following explain (page 354) command runs in “queryPlanner” (page 355) verbosity mode to return the query planning information for a count (page 213) command:
2.2. Database Commands
355
MongoDB Reference Manual, Release 2.8.0-rc3
db.runCommand(
{
explain: { count: "products", query: { quantity: { $gt: 50 } } },
verbosity: "queryPlanner"
}
)
executionStats Mode The following explain (page 354) operation runs in “executionStats” (page 355)
verbosity mode to return the query planning and execution information for a count (page 213) command:
db.runCommand(
{
explain: { count: "products", query: { quantity: { $gt: 50 } } },
verbosity: "executionStats"
}
)
allPlansExecution Mode By default, explain (page 354) runs in “allPlansExecution” (page 355) verbosity
mode. The following explain (page 354) command returns the queryPlanner and executionStats for all
considered plans for an update (page 251) command:
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.
db.runCommand(
{
explain: {
update: "products",
updates: [
{
q: { quantity: 1057, category: "apparel" },
u: { $set: { reorder: true } }
}
]
}
}
)
Output explain (page 354) operations can return information regarding:
• queryPlanner, which details the plan selected by the query optimizer and lists the rejected plans;
• executionStats, which details the execution of the winning plan and the rejected plans; and
• serverInfo, which provides information on the MongoDB instance.
The verbosity mode (i.e. queryPlanner, executionStats, allPlansExecution) determines whether the
results include executionStats and whether executionStats includes data captured during plan selection.
For details on the output, see http://docs.mongodb.org/manual/reference/explain-results.
features
features
features (page 356) is an internal command that returns the build-level feature settings.
356
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
getCmdLineOpts
getCmdLineOpts
The getCmdLineOpts (page 357) command returns a document containing command line options used to
start the given mongod (page 583) or mongos (page 601):
{ getCmdLineOpts: 1 }
This command returns a document with two fields, argv and parsed. The argv field contains an array with
each item from the command string used to invoke mongod (page 583) or mongos (page 601). The document
in the parsed field includes all runtime options, including those parsed from the command line and those
specified in the configuration file, if specified.
Consider the following example output of getCmdLineOpts (page 357):
{
"argv" : [
"/usr/bin/mongod",
"--config",
"/etc/mongodb.conf",
"--fork"
],
"parsed" : {
"bind_ip" : "127.0.0.1",
"config" : "/etc/mongodb/mongodb.conf",
"dbpath" : "/srv/mongodb",
"fork" : true,
"logappend" : "true",
"logpath" : "/var/log/mongodb/mongod.log",
"quiet" : "true"
},
"ok" : 1
}
getLog
getLog
The getLog (page 357) command returns a document with a log array that contains recent messages from the
mongod (page 583) process log. The getLog (page 357) command has the following syntax:
{ getLog: <log> }
Replace <log> with one of the following values:
•global - returns the combined output of all recent log entries.
•rs - if the mongod (page 583) is part of a replica set, getLog (page 357) will return recent notices
related to replica set activity.
•startupWarnings - will return logs that may contain errors or warnings from MongoDB’s log from
when the current process started. If mongod (page 583) started without warnings, this filter may return an
empty array.
You may also specify an asterisk (e.g. *) as the <log> value to return a list of available log filters. The
following interaction from the mongo (page 610) shell connected to a replica set:
db.adminCommand({getLog: "*" })
{ "names" : [ "global", "rs", "startupWarnings" ], "ok" : 1 }
getLog (page 357) returns events from a RAM cache of the mongod (page 583) events and does not read log
data from the log file.
2.2. Database Commands
357
MongoDB Reference Manual, Release 2.8.0-rc3
hostInfo
hostInfo
New in version 2.2.
Returns A document with information about the underlying system that the mongod (page 583) or
mongos (page 601) runs on. Some of the returned fields are only included on some platforms.
You must run the hostInfo (page 358) command, which takes no arguments, against the admin database.
Consider the following invocations of hostInfo (page 358):
db.hostInfo()
db.adminCommand( { "hostInfo" : 1 } )
In the mongo (page 610) shell you can use db.hostInfo() (page 119) as a helper to access hostInfo
(page 358). The output of hostInfo (page 358) 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>",
"cpuFeatures" : "<string>",
"pageSize" : <number>,
"numPages" : <number>,
"maxOpenFiles" : <number>
},
"ok" : <return>
}
Consider the following documentation of these fields:
hostInfo
The document returned by the hostInfo (page 358).
hostInfo.system
A sub-document about the underlying environment of the system running the mongod (page 583) or
mongos (page 601)
hostInfo.system.currentTime
A time stamp of the current system time.
hostInfo.system.hostname
The system name, which should correspond to the output of hostname -f on Linux systems.
hostInfo.system.cpuAddrSize
A number reflecting the architecture of the system. Either 32 or 64.
358
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
hostInfo.system.memSizeMB
The total amount of system memory (RAM) in megabytes.
hostInfo.system.numCores
The total number of available logical processor cores.
hostInfo.system.cpuArch
A string that represents the system architecture. Either x86 or x86_64.
hostInfo.system.numaEnabled
A boolean value. false if NUMA is interleaved (i.e. disabled), otherwise true.
hostInfo.os
A sub-document that contains information about the operating system running the mongod (page 583)
and mongos (page 601).
hostInfo.os.type
A string representing the type of operating system, such as Linux or Windows.
hostInfo.os.name
If available, returns a display name for the operating system.
hostInfo.os.version
If available, returns the name of the distribution or operating system.
hostInfo.extra
A sub-document with extra information about the operating system and the underlying hardware. The
content of the extra (page 359) sub-document depends on the operating system.
hostInfo.extra.versionString
A complete string of the operating system version and identification. On Linux and OS X systems, this
contains output similar to uname -a.
hostInfo.extra.libcVersion
The release of the system libc.
libcVersion (page 359) only appears on Linux systems.
hostInfo.extra.kernelVersion
The release of the Linux kernel in current use.
kernelVersion (page 359) only appears on Linux systems.
hostInfo.extra.alwaysFullSync
alwaysFullSync (page 359) only appears on OS X systems.
hostInfo.extra.nfsAsync
nfsAsync (page 359) only appears on OS X systems.
hostInfo.extra.cpuFrequencyMHz
Reports the clock speed of the system’s processor in megahertz.
hostInfo.extra.cpuFeatures
Reports the processor feature flags. On Linux systems this the same information that /proc/cpuinfo
includes in the flags fields.
hostInfo.extra.pageSize
Reports the default system page size in bytes.
hostInfo.extra.numPages
numPages (page 359) only appears on Linux systems.
2.2. Database Commands
359
MongoDB Reference Manual, Release 2.8.0-rc3
hostInfo.extra.maxOpenFiles
Reports
the
current
system
limits
on
open
file
handles.
http://docs.mongodb.org/manual/reference/ulimit for more information.
See
maxOpenFiles (page 359) only appears on Linux systems.
hostInfo.extra.scheduler
Reports the active I/O scheduler. scheduler (page 360) only appears on OS X systems.
indexStats
Definition
indexStats
The indexStats (page 360) command aggregates statistics for the B-tree data structure that stores data for a
MongoDB index.
Warning: This command is not intended for production deployments.
The command can be run only on a mongod
--enableExperimentalIndexStatsCmd option.
(page
583)
instance
that
uses
the
To aggregate statistics, issue the command like so:
db.runCommand( { indexStats: "<collection>", index: "<index name>" } )
Output The db.collection.indexStats() (page 54) method and equivalent indexStats (page 360)
command aggregate statistics for the B-tree data structure that stores data for a MongoDB index. The commands
aggregate statistics firstly for the entire B-tree and secondly for each individual level of the B-tree. The output displays
the following values.
indexStats.index
The index name.
indexStats.version
The index version.
For more information on index version numbers, see the v option in
db.collection.ensureIndex() (page 30).
indexStats.isIdIndex
If true, the index is the default _id index for the collection.
indexStats.keyPattern
The indexed keys.
indexStats.storageNs
The namespace of the index’s underlying storage.
indexStats.bucketBodyBytes
The fixed size, in bytes, of a B-tree bucket in the index, not including the record header. All indexes for a given
version have the same value for this field. MongoDB allocates fixed size buckets on disk.
indexStats.depth
The number of levels in the B-tree, not including the root level.
indexStats.overall
This section of the output displays statistics for the entire B-tree.
indexStats.overall.numBuckets
The number of buckets in the entire B-tree, including all levels.
360
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
indexStats.overall.keyCount
Statistics about the number of keys in a bucket, evaluated on a per-bucket level.
indexStats.overall.usedKeyCount
Statistics about the number of used keys in a bucket, evaluated on a per-bucket level. Used keys are keys
not marked as deleted.
indexStats.overall.bsonRatio
Statistics about the percentage of the bucket body that is occupied by the key objects themselves, excluding
associated metadata.
For example, if you have the document { name:
}, the key object is the string Bob Smith.
"Bob Smith" } and an index on { name:
1
indexStats.overall.keyNodeRatio
Statistics about the percentage of the bucket body that is occupied by the key node objects (the metadata
and links pertaining to the keys). This does not include the key itself. In the current implementation, a key
node’s objects consist of: the pointer to the key data (in the same bucket), the pointer to the record the key
is for, and the pointer to a child bucket.
indexStats.overall.fillRatio
The sum of the bsonRatio (page 361) and the keyNodeRatio (page 361). This shows how full the
buckets are. This will be much higher for indexes with sequential inserts.
indexStats.perLevel
This section of the output displays statistics for each level of the B-tree separately, starting with the root level.
This section displays a different document for each B-tree level.
indexStats.perLevel.numBuckets
The number of buckets at this level of the B-tree.
indexStats.perLevel.keyCount
Statistics about the number of keys in a bucket, evaluated on a per-bucket level.
indexStats.perLevel.usedKeyCount
Statistics about the number of used keys in a bucket, evaluated on a per-bucket level. Used keys are keys
not marked as deleted.
indexStats.perLevel.bsonRatio
Statistics about the percentage of the bucket body that is occupied by the key objects themselves, excluding
associated metadata.
indexStats.perLevel.keyNodeRatio
Statistics about the percentage of the bucket body that is occupied by the key node objects (the metadata
and links pertaining to the keys).
indexStats.perLevel.fillRatio
The sum of the bsonRatio (page 361) and the keyNodeRatio (page 361). This shows how full the
buckets are. This will be much higher in the following cases:
•For indexes with sequential inserts, such as the _id index when using ObjectId keys.
•For indexes that were recently built in the foreground with existing data.
•If you recently ran compact (page 322) or --repair.
Example The following is an example of db.collection.indexStats() (page 54) and indexStats
(page 360) output.
2.2. Database Commands
361
MongoDB Reference Manual, Release 2.8.0-rc3
{
"index" : "type_1_traits_1",
"version" : 1,
"isIdIndex" : false,
"keyPattern" : {
"type" : 1,
"traits" : 1
},
"storageNs" : "test.animals.$type_1_traits_1",
"bucketBodyBytes" : 8154,
"depth" : 2,
"overall" : {
"numBuckets" : 45513,
"keyCount" : {
"count" : NumberLong(45513),
"mean" : 253.89602970579836,
"stddev" : 21.784799875240708,
"min" : 52,
"max" : 290,
"quantiles" : {
"0.01" : 201.99785091648775,
// ...
"0.99" : 289.9999655156967
}
},
"usedKeyCount" : {
"count" : NumberLong(45513),
// ...
"quantiles" : {
"0.01" : 201.99785091648775,
// ...
"0.99" : 289.9999655156967
}
},
"bsonRatio" : {
"count" : NumberLong(45513),
// ...
"quantiles" : {
"0.01" : 0.4267797891997124,
// ...
"0.99" : 0.5945548174629648
}
},
"keyNodeRatio" : {
"count" : NumberLong(45513),
// ...
"quantiles" : {
"0.01" : 0.3963656628236211,
// ...
"0.99" : 0.5690457993930765
}
},
"fillRatio" : {
"count" : NumberLong(45513),
// ...
"quantiles" : {
"0.01" : 0.9909134214926929,
// ...
362
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
"0.99" : 0.9960755457453732
}
}
},
"perLevel" : [
{
"numBuckets" : 1,
"keyCount" : {
"count" : NumberLong(1),
"mean" : 180,
"stddev" : 0,
"min" : 180,
"max" : 180
},
"usedKeyCount" : {
"count" : NumberLong(1),
// ...
"max" : 180
},
"bsonRatio" : {
"count" : NumberLong(1),
// ...
"max" : 0.3619082658817758
},
"keyNodeRatio" : {
"count" : NumberLong(1),
// ...
"max" : 0.35320088300220753
},
"fillRatio" : {
"count" : NumberLong(1),
// ...
"max" : 0.7151091488839834
}
},
{
"numBuckets" : 180,
"keyCount" : {
"count" : NumberLong(180),
"mean" : 250.84444444444443,
"stddev" : 26.30057503009355,
"min" : 52,
"max" : 290
},
"usedKeyCount" : {
"count" : NumberLong(180),
// ...
"max" : 290
},
"bsonRatio" : {
"count" : NumberLong(180),
// ...
"max" : 0.5945548197203826
},
"keyNodeRatio" : {
"count" : NumberLong(180),
// ...
"max" : 0.5690458670591121
2.2. Database Commands
363
MongoDB Reference Manual, Release 2.8.0-rc3
},
"fillRatio" : {
"count" : NumberLong(180),
// ...
"max" : 0.9963208241353937
}
},
{
"numBuckets" : 45332,
"keyCount" : {
"count" : NumberLong(45332),
"mean" : 253.90977675813994,
"stddev" : 21.761620836279018,
"min" : 167,
"max" : 290,
"quantiles" : {
"0.01" : 202.0000012563603,
// ...
"0.99" : 289.99996486571894
}
},
"usedKeyCount" : {
"count" : NumberLong(45332),
// ...
"quantiles" : {
"0.01" : 202.0000012563603,
// ...
"0.99" : 289.99996486571894
}
},
"bsonRatio" : {
"count" : NumberLong(45332),
// ...
"quantiles" : {
"0.01" : 0.42678446958950583,
// ...
"0.99" : 0.5945548175411283
}
},
"keyNodeRatio" : {
"count" : NumberLong(45332),
// ...
"quantiles" : {
"0.01" : 0.39636988227885306,
// ...
"0.99" : 0.5690457981176729
}
},
"fillRatio" : {
"count" : NumberLong(45332),
// ...
"quantiles" : {
"0.01" : 0.9909246995605362,
// ...
"0.99" : 0.996075546919481
}
}
}
364
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
],
"ok" : 1
}
Additional Resources For more information on the command’s limits and output, see the following:
• The equivalent db.collection.indexStats() (page 54) method,
• indexStats (page 360), and
• https://github.com/10gen-labs/storage-viz#readme.
isSelf
_isSelf
_isSelf (page 365) is an internal command.
listCommands
listCommands
The listCommands (page 365) command generates a list of all database commands implemented for the
current mongod (page 583) instance.
listDatabases
listDatabases
The listDatabases (page 365) command provides a list of existing databases along with basic statistics
about them:
{ listDatabases: 1 }
The value (e.g. 1) does not affect the output of the command. listDatabases (page 365) returns a document
for each database. Each document contains a name field with the database name, a sizeOnDisk field with
the total size of the database file on disk in bytes, and an empty field specifying whether the database has any
data.
Example
The following operation returns a list of all databases:
db.runCommand( { listDatabases: 1 } )
See also:
http://docs.mongodb.org/manual/tutorial/use-database-commands.
netstat
netstat
netstat (page 365) is an internal command that is only available on mongos (page 601) instances.
ping
ping
The ping (page 365) command is a no-op used to test whether a server is responding to commands. This
command will return immediately even if the server is write-locked:
2.2. Database Commands
365
MongoDB Reference Manual, Release 2.8.0-rc3
{ ping: 1 }
The value (e.g. 1 above) does not impact the behavior of the command.
profile
profile
Use the profile (page 366) command to enable, disable, or change the query profiling level. This allows
administrators to capture data regarding performance. The database profiling system can impact performance
and can allow the server to write the contents of queries to the log. Your deployment should carefully consider
the security implications of this. Consider the following prototype syntax:
{ profile: <level> }
The following profiling levels are available:
Level
-1
0
1
2
Setting
No change. Returns the current profile level.
Off. No profiling.
On. Only includes slow operations.
On. Includes all operations.
You may optionally set a threshold in milliseconds for profiling using the slowms option, as follows:
{ profile: 1, slowms: 200 }
mongod (page 583) writes the output of the database profiler to the system.profile collection.
mongod (page 583) records queries that take longer than the slowOpThresholdMs to the server log even
when the database profiler is not active.
See also:
Additional documentation regarding Database Profiling.
See also:
“db.getProfilingStatus() (page 117)” and “db.setProfilingLevel() (page 126)” provide
wrappers around this functionality in the mongo (page 610) shell.
Note: This command obtains a write lock on the affected database and will block other operations until it has
completed. However, the write lock is only held while enabling or disabling the profiler. This is typically a short
operation.
serverStatus
Definition
serverStatus
The serverStatus (page 366) command returns a document that provides an overview of the database
process’s state. Most monitoring applications run this command at a regular interval to collection statistics
about the instance:
{ serverStatus: 1 }
The value (i.e. 1 above), does not affect the operation of the command.
Changed in version 2.4: In 2.4 you can dynamically suppress portions of the serverStatus (page 366)
output, or include suppressed sections by adding fields to the command document as in the following examples:
366
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.runCommand( { serverStatus: 1, repl: 0, indexCounters: 0 } )
db.runCommand( { serverStatus: 1, workingSet: 1, metrics: 0, locks: 0 } )
serverStatus (page 366) includes all fields by default, except workingSet (page 381) rangeDeleter
(page 377), and some content in the repl (page 374) document.
Note: You may only dynamically include top-level fields from the serverStatus (page 366) document that are
not included by default. You can exclude any field that serverStatus (page 366) includes by default.
See also:
db.serverStatus() (page 124)
Output The serverStatus (page 366) command returns a collection of information that reflects the database’s
status. These data are useful for diagnosing and assessing the performance of your MongoDB instance. This reference
catalogs each datum included in the output of this command and provides context for using this data to more effectively
administer your database.
See also:
Much of the output of serverStatus (page 366) is also displayed dynamically by mongostat (page 657). See
the mongostat (page 657) command for more information.
For examples of the serverStatus (page 366) output, see http://docs.mongodb.org/manual/reference/server-st
Instance Information For an example of the instance information, see the Instance Information section of the
http://docs.mongodb.org/manual/reference/server-status page.
serverStatus.host
The host (page 367) field contains the system’s hostname. In Unix/Linux systems, this should be the same as
the output of the hostname command.
serverStatus.version
The version (page 367) field contains the version of MongoDB running on the current mongod (page 583)
or mongos (page 601) instance.
serverStatus.process
The process (page 367) field identifies which kind of MongoDB instance is running. Possible values are:
•mongos (page 601)
•mongod (page 583)
serverStatus.uptime
The value of the uptime (page 367) field corresponds to the number of seconds that the mongos (page 601)
or mongod (page 583) process has been active.
serverStatus.uptimeEstimate
uptimeEstimate (page 367) provides the uptime as calculated from MongoDB’s internal course-grained
time keeping system.
serverStatus.localTime
The localTime (page 367) value is the current time, according to the server, in UTC specified in an ISODate
format.
2.2. Database Commands
367
MongoDB Reference Manual, Release 2.8.0-rc3
locks New in version 2.1.2: All locks (page 368) statuses first appeared in the 2.1.2 development release for the
2.2 series.
For
an
example
of
the
locks
output,
see
the
locks
http://docs.mongodb.org/manual/reference/server-status page.
section
of
the
serverStatus.locks
The locks (page 368) document contains sub-documents that provides a granular report on MongoDB
database-level lock use. All values are of the NumberLong() type.
Generally, fields named:
•R refer to the global read lock,
•W refer to the global write lock,
•r refer to the database specific read lock, and
•w refer to the database specific write lock.
If a document does not have any fields, it means that no locks have existed with this context since the last time
the mongod (page 583) started.
serverStatus.locks..
A field named . holds the first document in locks (page 368) that contains information about the global lock.
serverStatus.locks...timeLockedMicros
The timeLockedMicros (page 368) document reports the amount of time in microseconds that a lock has
existed in all databases in this mongod (page 583) instance.
serverStatus.locks...timeLockedMicros.R
The R field reports the amount of time in microseconds that any database has held the global read lock.
serverStatus.locks...timeLockedMicros.W
The W field reports the amount of time in microseconds that any database has held the global write lock.
serverStatus.locks...timeLockedMicros.r
The r field reports the amount of time in microseconds that any database has held the local read lock.
serverStatus.locks...timeLockedMicros.w
The w field reports the amount of time in microseconds that any database has held the local write lock.
serverStatus.locks...timeAcquiringMicros
The timeAcquiringMicros (page 368) document reports the amount of time in microseconds that operations have spent waiting to acquire a lock in all databases in this mongod (page 583) instance.
serverStatus.locks...timeAcquiringMicros.R
The R field reports the amount of time in microseconds that any database has spent waiting for the global read
lock.
serverStatus.locks...timeAcquiringMicros.W
The W field reports the amount of time in microseconds that any database has spent waiting for the global write
lock.
serverStatus.locks.admin
The admin (page 368) document contains two sub-documents that report data regarding lock use in the admin
database.
serverStatus.locks.admin.timeLockedMicros
The timeLockedMicros (page 368) document reports the amount of time in microseconds that locks have
existed in the context of the admin database.
serverStatus.locks.admin.timeLockedMicros.r
The r field reports the amount of time in microseconds that the admin database has held the read lock.
368
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
serverStatus.locks.admin.timeLockedMicros.w
The w field reports the amount of time in microseconds that the admin database has held the write lock.
serverStatus.locks.admin.timeAcquiringMicros
The timeAcquiringMicros (page 369) document reports on the amount of field time in microseconds that
operations have spent waiting to acquire a lock for the admin database.
serverStatus.locks.admin.timeAcquiringMicros.r
The r field reports the amount of time in microseconds that operations have spent waiting to acquire a read lock
on the admin database.
serverStatus.locks.admin.timeAcquiringMicros.w
The w field reports the amount of time in microseconds that operations have spent waiting to acquire a write
lock on the admin database.
serverStatus.locks.local
The local (page 369) document contains two sub-documents that report data regarding lock use in the local
database. The local database contains a number of instance specific data, including the oplog for replication.
serverStatus.locks.local.timeLockedMicros
The timeLockedMicros (page 369) document reports on the amount of time in microseconds that locks
have existed in the context of the local database.
serverStatus.locks.local.timeLockedMicros.r
The r field reports the amount of time in microseconds that the local database has held the read lock.
serverStatus.locks.local.timeLockedMicros.w
The w field reports the amount of time in microseconds that the local database has held the write lock.
serverStatus.locks.local.timeAcquiringMicros
The timeAcquiringMicros (page 369) document reports on the amount of time in microseconds that
operations have spent waiting to acquire a lock for the local database.
serverStatus.locks.local.timeAcquiringMicros.r
The r field reports the amount of time in microseconds that operations have spent waiting to acquire a read lock
on the local database.
serverStatus.locks.local.timeAcquiringMicros.w
The w field reports the amount of time in microseconds that operations have spent waiting to acquire a write
lock on the local database.
serverStatus.locks.<database>
For each additional database locks (page 368) includes a document that reports on the lock use for this
database. The names of these documents reflect the database name itself.
serverStatus.locks.<database>.timeLockedMicros
The timeLockedMicros (page 369) document reports on the amount of time in microseconds that locks
have existed in the context of the <database> database.
serverStatus.locks.<database>.timeLockedMicros.r
The r field reports the amount of time in microseconds that the <database> database has held the read lock.
serverStatus.locks.<database>.timeLockedMicros.w
The w field reports the amount of time in microseconds that the <database> database has held the write lock.
serverStatus.locks.<database>.timeAcquiringMicros
The timeAcquiringMicros (page 369) document reports on the amount of time in microseconds that
operations have spent waiting to acquire a lock for the <database> database.
serverStatus.locks.<database>.timeAcquiringMicros.r
The r field reports the amount of time in microseconds that operations have spent waiting to acquire a read lock
on the <database> database.
2.2. Database Commands
369
MongoDB Reference Manual, Release 2.8.0-rc3
serverStatus.locks.<database>.timeAcquiringMicros.w
The w field reports the amount of time in microseconds that operations have spent waiting to acquire a write
lock on the <database> database.
globalLock For an example of the globalLock output, see the globalLock
http://docs.mongodb.org/manual/reference/server-status page.
section
of
the
serverStatus.globalLock
The globalLock (page 370) data structure contains information regarding the database’s current lock state,
historical lock status, current operation queue, and the number of active clients.
serverStatus.globalLock.totalTime
The value of totalTime (page 370) represents the time, in microseconds, since the database last started and
creation of the globalLock (page 370). This is roughly equivalent to total server uptime.
serverStatus.globalLock.lockTime
The value of lockTime (page 370) represents the time, in microseconds, since the database last started, that
the globalLock (page 370) has been held.
Consider this value in combination with the value of totalTime (page 370). MongoDB aggregates these
values in the ratio (page 370) value. If the ratio (page 370) value is small but totalTime (page 370) is
high the globalLock (page 370) has typically been held frequently for shorter periods of time, which may be
indicative of a more normal use pattern. If the lockTime (page 370) is higher and the totalTime (page 370)
is smaller (relatively) then fewer operations are responsible for a greater portion of server’s use (relatively).
serverStatus.globalLock.ratio
Changed in version 2.2: ratio (page 370) was removed. See locks (page 368).
The value of ratio (page 370) displays the relationship between lockTime (page 370) and totalTime
(page 370).
Low values indicate that operations have held the globalLock (page 370) frequently for shorter periods of
time. High values indicate that operations have held globalLock (page 370) infrequently for longer periods
of time.
serverStatus.globalLock.currentQueue
The currentQueue (page 370) data structure value provides more granular information concerning the number of operations queued because of a lock.
serverStatus.globalLock.currentQueue.total
The value of total (page 370) provides a combined total of operations queued waiting for the lock.
A consistently small queue, particularly of shorter operations should cause no concern. Also, consider this value
in light of the size of queue waiting for the read lock (e.g. readers (page 370)) and write lock (e.g. writers
(page 370)) individually.
serverStatus.globalLock.currentQueue.readers
The value of readers (page 370) is the number of operations that are currently queued and waiting for the
read lock. A consistently small read-queue, particularly of shorter operations should cause no concern.
serverStatus.globalLock.currentQueue.writers
The value of writers (page 370) is the number of operations that are currently queued and waiting for the
write lock. A consistently small write-queue, particularly of shorter operations is no cause for concern.
globalLock.activeClients
serverStatus.globalLock.activeClients
The activeClients (page 370) data structure provides more granular information about the number of
connected clients and the operation types (e.g. read or write) performed by these clients.
370
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Use this data to provide context for the currentQueue (page 370) data.
serverStatus.globalLock.activeClients.total
The value of total (page 371) is the total number of active client connections to the database. This combines
clients that are performing read operations (e.g. readers (page 371)) and clients that are performing write
operations (e.g. writers (page 371)).
serverStatus.globalLock.activeClients.readers
The value of readers (page 371) contains a count of the active client connections performing read operations.
serverStatus.globalLock.activeClients.writers
The value of writers (page 371) contains a count of active client connections performing write operations.
mem For
an
example
of
the
mem
output,
see
the
mem
http://docs.mongodb.org/manual/reference/server-status page.
section
of
the
serverStatus.mem
The mem (page 371) data structure holds information regarding the target system architecture of mongod
(page 583) and current memory use.
serverStatus.mem.bits
The value of bits (page 371) is either 64 or 32, depending on which target architecture specified during the
mongod (page 583) compilation process. In most instances this is 64, and this value does not change over time.
serverStatus.mem.resident
The value of resident (page 371) is roughly equivalent to the amount of RAM, in megabytes (MB), currently
used by the database process. In normal use this value tends to grow. In dedicated database servers this number
tends to approach the total amount of system memory.
serverStatus.mem.virtual
virtual (page 371) displays the quantity, in megabytes (MB), of virtual memory used by the mongod
(page 583) process. With journaling enabled, the value of virtual (page 371) is at least twice the value
of mapped (page 371).
If virtual (page 371) value is significantly larger than mapped (page 371) (e.g. 3 or more times), this may
indicate a memory leak.
serverStatus.mem.supported
supported (page 371) is true when the underlying system supports extended memory information. If this
value is false and the system does not support extended memory information, then other mem (page 371) values
may not be accessible to the database server.
serverStatus.mem.mapped
The value of mapped (page 371) provides the amount of mapped memory, in megabytes (MB), by the database.
Because MongoDB uses memory-mapped files, this value is likely to be to be roughly equivalent to the total
size of your database or databases.
serverStatus.mem.mappedWithJournal
mappedWithJournal (page 371) provides the amount of mapped memory, in megabytes (MB), including
the memory used for journaling. This value will always be twice the value of mapped (page 371). This field is
only included if journaling is enabled.
connections For an example of the connections output, see the connections section of the
http://docs.mongodb.org/manual/reference/server-status page.
serverStatus.connections
The connections (page 371) sub document data regarding the current status of incoming connections and
availability of the database server. Use these values to assess the current load and capacity requirements of the
server.
2.2. Database Commands
371
MongoDB Reference Manual, Release 2.8.0-rc3
serverStatus.connections.current
The value of current (page 371) corresponds to the number of connections to the database server from
clients. This number includes the current shell session. Consider the value of available (page 372) to add
more context to this datum.
This figure will include all incoming connections including any shell connections or connections from other
servers, such as replica set members or mongos (page 601) instances.
serverStatus.connections.available
available (page 372) provides a count of the number of unused available incoming connections the database
can provide. Consider this value in combination with the value of current (page 371) to understand the
connection load on the database, and the http://docs.mongodb.org/manual/reference/ulimit
document for more information about system thresholds on available connections.
serverStatus.connections.totalCreated
totalCreated (page 372) provides a count of all incoming connections created to the server. This number
includes connections that have since closed.
extra_info For an example of the extra_info output, see the extra_info
http://docs.mongodb.org/manual/reference/server-status page.
section
of
the
serverStatus.extra_info
The extra_info (page 372) data structure holds data collected by the mongod (page 583) instance about the
underlying system. Your system may only report a subset of these fields.
serverStatus.extra_info.note
The field note (page 372) reports that the data in this structure depend on the underlying platform, and has the
text: “fields vary by platform.”
serverStatus.extra_info.heap_usage_bytes
The heap_usage_bytes (page 372) field is only available on Unix/Linux systems, and reports the total size
in bytes of heap space used by the database process.
serverStatus.extra_info.page_faults
The page_faults (page 372) Reports the total number of page faults that require disk operations. Page
faults refer to operations that require the database server to access data which isn’t available in active memory.
The page_faults (page 372) counter may increase dramatically during moments of poor performance and
may correlate with limited memory environments and larger data sets. Limited and sporadic page faults do not
necessarily indicate an issue.
indexCounters For an example of the indexCounters output, see the indexCounters section of the
http://docs.mongodb.org/manual/reference/server-status page.
serverStatus.indexCounters
Changed in version 2.2: Previously, data in the indexCounters (page 372) document reported sampled data,
and were only useful in relative comparison to each other, because they could not reflect absolute index use. In
2.2 and later, these data reflect actual index use.
Changed in version 2.4: Fields previously in the btree sub-document of indexCounters (page 372) are
now fields in the indexCounters (page 372) document.
The indexCounters (page 372) data structure reports information regarding the state and use of indexes in
MongoDB.
serverStatus.indexCounters.accesses
accesses (page 372) reports the number of times that operations have accessed indexes. This value is the
combination of the hits (page 373) and misses (page 373). Higher values indicate that your database has
372
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
indexes and that queries are taking advantage of these indexes. If this number does not grow over time, this
might indicate that your indexes do not effectively support your use.
serverStatus.indexCounters.hits
The hits (page 373) value reflects the number of times that an index has been accessed and mongod (page 583)
is able to return the index from memory.
A higher value indicates effective index use. hits (page 373) values that represent a greater proportion of the
accesses (page 372) value, tend to indicate more effective index configuration.
serverStatus.indexCounters.misses
The misses (page 373) value represents the number of times that an operation attempted to access an index
that was not in memory. These “misses,” do not indicate a failed query or operation, but rather an inefficient use
of the index. Lower values in this field indicate better index use and likely overall performance as well.
serverStatus.indexCounters.resets
The resets (page 373) value reflects the number of times that the index counters have been reset since the
database last restarted. Typically this value is 0, but use this value to provide context for the data specified by
other indexCounters (page 372) values.
serverStatus.indexCounters.missRatio
The missRatio (page 373) value is the ratio of hits (page 373) to misses (page 373). This value is
typically 0 or approaching 0.
backgroundFlushing For an example of the backgroundFlushing output, see the backgroundFlushing section
of the http://docs.mongodb.org/manual/reference/server-status page.
serverStatus.backgroundFlushing
mongod (page 583) periodically flushes writes to disk. In the default configuration, this happens every 60
seconds. The backgroundFlushing (page 373) data structure contains data regarding these operations.
Consider these values if you have concerns about write performance and journaling (page 379).
serverStatus.backgroundFlushing.flushes
flushes (page 373) is a counter that collects the number of times the database has flushed all writes to disk.
This value will grow as database runs for longer periods of time.
serverStatus.backgroundFlushing.total_ms
The total_ms (page 373) value provides the total number of milliseconds (ms) that the mongod (page 583)
processes have spent writing (i.e. flushing) data to disk. Because this is an absolute value, consider the value of
flushes (page 373) and average_ms (page 373) to provide better context for this datum.
serverStatus.backgroundFlushing.average_ms
The average_ms (page 373) value describes the relationship between the number of flushes and the total
amount of time that the database has spent writing data to disk. The larger flushes (page 373) is, the more
likely this value is likely to represent a “normal,” time; however, abnormal data can skew this value.
Use the last_ms (page 373) to ensure that a high average is not skewed by transient historical issue or a
random write distribution.
serverStatus.backgroundFlushing.last_ms
The value of the last_ms (page 373) field is the amount of time, in milliseconds, that the last flush operation
took to complete. Use this value to verify that the current performance of the server and is in line with the
historical data provided by average_ms (page 373) and total_ms (page 373).
serverStatus.backgroundFlushing.last_finished
The last_finished (page 373) field provides a timestamp of the last completed flush operation in the
ISODate format. If this value is more than a few minutes old relative to your server’s current time and accounting
for differences in time zone, restarting the database may result in some data loss.
Also consider ongoing operations that might skew this value by routinely block write operations.
2.2. Database Commands
373
MongoDB Reference Manual, Release 2.8.0-rc3
cursors Deprecated since version 2.6: See the serverStatus.metrics.cursor (page 382) field instead.
For
an
example
of
the
cursors
output,
see
the
cursors
http://docs.mongodb.org/manual/reference/server-status page.
of
section
the
serverStatus.cursors
The cursors (page 374) data structure contains data regarding cursor state and use.
serverStatus.cursors.note
A note specifying to use the serverStatus.metrics.cursor (page 385) field instead of
serverStatus.cursors (page 374).
serverStatus.cursors.totalOpen
totalOpen (page 374) provides the number of cursors that MongoDB is maintaining for clients. Because
MongoDB exhausts unused cursors, typically this value small or zero. However, if there is a queue, stale
tailable cursor, or a large number of operations, this value may rise.
serverStatus.cursors.clientCursors_size
Deprecated since version 1.x: See totalOpen (page 374) for this datum.
serverStatus.cursors.timedOut
timedOut (page 374) provides a counter of the total number of cursors that have timed out since the server
process started. If this number is large or growing at a regular rate, this may indicate an application error.
serverStatus.cursors.totalNoTimeout
totalNoTimeout (page 374) provides the number of open cursors with
DBQuery.Option.noTimeout (page 82) set to prevent timeout after a period of inactivity.
the
option
serverStatus.cursors.pinned
serverStatus.cursors.pinned (page 374) provides the number of “pinned” open cursors.
network For an example of the network output,
see the network
http://docs.mongodb.org/manual/reference/server-status page.
section
of
the
serverStatus.network
The network (page 374) data structure contains data regarding MongoDB’s network use.
serverStatus.network.bytesIn
The value of the bytesIn (page 374) field reflects the amount of network traffic, in bytes, received by this
database. Use this value to ensure that network traffic sent to the mongod (page 583) process is consistent with
expectations and overall inter-application traffic.
serverStatus.network.bytesOut
The value of the bytesOut (page 374) field reflects the amount of network traffic, in bytes, sent from this
database. Use this value to ensure that network traffic sent by the mongod (page 583) process is consistent with
expectations and overall inter-application traffic.
serverStatus.network.numRequests
The numRequests (page 374) field is a counter of the total number of distinct requests that the server has
received. Use this value to provide context for the bytesIn (page 374) and bytesOut (page 374) values to
ensure that MongoDB’s network utilization is consistent with expectations and application use.
repl For
an
example
of
the
repl
output,
see
the
repl
http://docs.mongodb.org/manual/reference/server-status page.
section
of
the
serverStatus.repl
The repl (page 374) data structure contains status information for MongoDB’s replication (i.e. “replica set”)
configuration. These values only appear when the current host has replication enabled.
See http://docs.mongodb.org/manual/replication for more information on replication.
374
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
serverStatus.repl.setName
The setName (page 375) field contains a string with the name of the current replica set. This value reflects the
--replSet command line argument, or replSetName value in the configuration file.
See http://docs.mongodb.org/manual/replication for more information on replication.
serverStatus.repl.ismaster
The value of the ismaster (page 375) field is either true or false and reflects whether the current node is
the master or primary node in the replica set.
See http://docs.mongodb.org/manual/replication for more information on replication.
serverStatus.repl.secondary
The value of the secondary (page 375) field is either true or false and reflects whether the current node
is a secondary node in the replica set.
See http://docs.mongodb.org/manual/replication for more information on replication.
serverStatus.repl.primary
New in version 2.8.0.
A string in the format of "[hostname]:[port]" listing the current primary member of the replica set.
serverStatus.repl.hosts
hosts (page 375) is an array that lists the other nodes in the current replica set. Each member of the replica set
appears in the form of hostname:port.
See http://docs.mongodb.org/manual/replication for more information on replication.
serverStatus.repl.me
New in version 2.8.0.
The [hostname]:[port] combination for the current member in the replica set.
serverStatus.repl.rabid
New in version 2.8.0.
Rollback identifier. Used to determine if a rollback has happened for this mongod (page 583) instance.
serverStatus.repl.slaves
New in version 2.8.0.
An array with one document for every member of the replica set that reports replication process to this member.
Typically this is the primary, or secondaries if using chained replication.
To include this output you must pass the��repl�� option to the:dbcommand:serverStatus, as in the following:
db.serverStatus({ "repl": 1 })
db.runCommand({ "serverStatus": 1, "repl": 1 })
The content of the slaves (page 375) section depends on the source of each member’s replication. This section
supports internal operation and is for internal and diagnostic use only.
serverStatus.repl.slaves[n].rid
An ID in the form of an ObjectId of the member’s� of the replica set. For internal use only.
serverStatus.repl.slaves[n].host
The name of the host in [hostname]:[port] format for the member of the replica set.
serverStatus.repl.slaves[n].optime
Information regarding the last operation from the oplog that the member applied, as reported from this member.
serverStatus.repl.slaves[n].memberID
The integer identifier for this member of the replica set.
2.2. Database Commands
375
MongoDB Reference Manual, Release 2.8.0-rc3
opcountersRepl For an example of the opcountersRepl output, see the opcountersRepl section of the
http://docs.mongodb.org/manual/reference/server-status page.
serverStatus.opcountersRepl
The opcountersRepl (page 376) data structure, similar to the opcounters (page 376) data structure,
provides an overview of database replication operations by type and makes it possible to analyze the load on the
replica in more granular manner. These values only appear when the current host has replication enabled.
These values will differ from the opcounters (page 376) values because of how MongoDB serializes operations during replication. See http://docs.mongodb.org/manual/replication for more information on replication.
These numbers will grow over time in response to database use. Analyze these values over time to track database
utilization.
serverStatus.opcountersRepl.insert
insert (page 376) provides a counter of the total number of replicated insert operations since the mongod
(page 583) instance last started.
serverStatus.opcountersRepl.query
query (page 376) provides a counter of the total number of replicated queries since the mongod (page 583)
instance last started.
serverStatus.opcountersRepl.update
update (page 376) provides a counter of the total number of replicated update operations since the mongod
(page 583) instance last started.
serverStatus.opcountersRepl.delete
delete (page 376) provides a counter of the total number of replicated delete operations since the mongod
(page 583) instance last started.
serverStatus.opcountersRepl.getmore
getmore (page 376) provides a counter of the total number of “getmore” operations since the mongod
(page 583) instance last started. This counter can be high even if the query count is low. Secondary nodes
send getMore operations as part of the replication process.
serverStatus.opcountersRepl.command
command (page 376) provides a counter of the total number of replicated commands issued to the database
since the mongod (page 583) instance last started.
opcounters For an example of the opcounters output, see the opcounters
http://docs.mongodb.org/manual/reference/server-status page.
section
of
the
serverStatus.opcounters
The opcounters (page 376) data structure provides an overview of database operations by type and makes it
possible to analyze the load on the database in more granular manner.
These numbers will grow over time and in response to database use. Analyze these values over time to track
database utilization.
Note: The data in opcounters (page 376) treats operations that affect multiple documents, such as bulk insert
or multi-update operations, as a single operation. See document (page 382) for more granular document-level
operation tracking.
Additionally, these values reflect received operations, and increment even when operations are not successful.
serverStatus.opcounters.insert
insert (page 376) provides a counter of the total number of insert operations received since the mongod
(page 583) instance last started.
376
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
serverStatus.opcounters.query
query (page 376) provides a counter of the total number of queries received since the mongod (page 583)
instance last started.
serverStatus.opcounters.update
update (page 377) provides a counter of the total number of update operations recieved since the mongod
(page 583) instance last started.
serverStatus.opcounters.delete
delete (page 377) provides a counter of the total number of delete operations since the mongod (page 583)
instance last started.
serverStatus.opcounters.getmore
getmore (page 377) provides a counter of the total number of “getmore” operations since the mongod
(page 583) instance last started. This counter can be high even if the query count is low. Secondary nodes
send getMore operations as part of the replication process.
serverStatus.opcounters.command
command (page 377) provides a counter of the total number of commands issued to the database since the
mongod (page 583) instance last started.
rangeDeleter New in version 2.8.0.
Note: The rangeDeleter (page 377) data is only included in the output of serverStatus (page 366) if
explicitly enabled. To return the rangeDeleter (page 377), use one of the following commands:
db.serverStatus( { rangeDeleter: 1 } )
db.runCommand( { serverStatus: 1, rangeDeleter: 1 } )
serverStatus.rangeDeleter
A document that reports on the work performed by the cleanupOrphaned (page 305) command and the
cleanup phase of the moveChunk (page 310) command.
serverStatus.rangeDeleter.lastDeleteStats
An array of documents that each report on the last operations of migration cleanup operations. At most
lastDeleteStats (page 377) will report data for the last 10 operations.
serverStatus.rangeDeleter.lastDeleteStats[n].deletedDocs
A counter with the number of documents deleted by migration cleanup operations.
serverStatus.rangeDeleter.lastDeleteStats[n].queueStart
A timestamp that reflects when operations began entering the queue for the migration cleanup operation. Specifically, operations wait in the queue while the mongod (page 583) waits for open cursors to close on the namespace.
serverStatus.rangeDeleter.lastDeleteStats[n].queueEnd
A timestamp that reflects when the migration cleanup operation begins.
serverStatus.rangeDeleter.lastDeleteStats[n].deleteStart
A timestamp for the beginning of the delete process that is part of the migration cleanup operation.
serverStatus.rangeDeleter.lastDeleteStats[n].deleteEnd
A timestamp for the end of the delete process that is part of the migration cleanup operation.
serverStatus.rangeDeleter.lastDeleteStats[n].waitForReplStart
A timestamp that reflects when the migration cleanup operation began waiting for replication to process the
delete operation.
2.2. Database Commands
377
MongoDB Reference Manual, Release 2.8.0-rc3
serverStatus.rangeDeleter.lastDeleteStats[n].waitForReplEnd
A timestamp that reflects when the migration cleanup operation finished waiting for replication to process the
delete operation.
security New in version 2.8.0.
For
an
example
of
the
security
output,
see
the
security
http://docs.mongodb.org/manual/reference/server-status page.
section
of
the
severStatus.security
A document reporting security configuration and details. Only appears for mongod (page 583) instances compiled with support for SSL.
severStatus.security.SSLServerSubjectName
The subject name associated with the SSL certificate specified by net.ssl.PEMKeyPassword.
severStatus.security.SSLServerHasCertificateAuthority
A boolean that is true when the SSL certificate specified by net.ssl.PEMKeyPassword is associated
with a certificate authority. false when the SSL certificate is self-signed.
severStatus.security.SSLServerCertificateExpirationDate
A date object object that represents the date when the SSL
net.ssl.PEMKeyPassword expires.
certificate
specified
by
storageEngine New in version 2.8.0.
For an example of the storageEngine output,
see the storageEngine
http://docs.mongodb.org/manual/reference/server-status page.
section
of
the
of
the
serverStatus.storageEngine
A document with data about the current storage engine.
serverStatus.storageEngine.name
A string that represents the name of the current storage engine.
asserts For an example of the asserts output,
see the asserts
http://docs.mongodb.org/manual/reference/server-status page.
section
serverStatus.asserts
The asserts (page 378) document reports the number of asserts on the database. While assert errors are
typically uncommon, if there are non-zero values for the asserts (page 378), you should check the log file
for the mongod (page 583) process for more information. In many cases these errors are trivial, but are worth
investigating.
serverStatus.asserts.regular
The regular (page 378) counter tracks the number of regular assertions raised since the server process started.
Check the log file for more information about these messages.
serverStatus.asserts.warning
The warning (page 378) counter tracks the number of warnings raised since the server process started. Check
the log file for more information about these warnings.
serverStatus.asserts.msg
The msg (page 378) counter tracks the number of message assertions raised since the server process started.
Check the log file for more information about these messages.
serverStatus.asserts.user
The user (page 378) counter reports the number of “user asserts” that have occurred since the last time the
378
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
server process started. These are errors that user may generate, such as out of disk space or duplicate key. You
can prevent these assertions by fixing a problem with your application or deployment. Check the MongoDB log
for more information.
serverStatus.asserts.rollovers
The rollovers (page 379) counter displays the number of times that the rollover counters have rolled over
since the last time the server process started. The counters will rollover to zero after 230 assertions. Use this
value to provide context to the other values in the asserts (page 378) data structure.
writeBacksQueued For an example of the writeBacksQueued output, see the writeBacksQueued section of the
http://docs.mongodb.org/manual/reference/server-status page.
serverStatus.writeBacksQueued
The value of writeBacksQueued (page 379) is true when there are operations from a mongos (page 601)
instance queued for retrying. Typically this option is false.
See also:
writeBacks
Journaling (dur) New in version 1.8.
For an example of the Journaling (dur) output, see the journaling
http://docs.mongodb.org/manual/reference/server-status page.
section
of
the
serverStatus.dur
The dur (page 379) (for “durability”) document contains data regarding the mongod (page 583)�s journalingrelated operations and performance. mongod (page 583) must be running with journaling for these data to
appear in the output of “serverStatus (page 366)”.
MongoDB reports the data in dur (page 379) based on 3 second intervals of data, collected between 3 and 6
seconds in the past.
See also:
http://docs.mongodb.org/manual/core/journaling for more information about journaling operations.
serverStatus.dur.commits
The commits (page 379) provides the number of transactions written to the journal during the last journal
group commit interval.
serverStatus.dur.journaledMB
The journaledMB (page 379) provides the amount of data in megabytes (MB) written to journal during the
last journal group commit interval.
serverStatus.dur.writeToDataFilesMB
The writeToDataFilesMB (page 379) provides the amount of data in megabytes (MB) written from journal
to the data files during the last journal group commit interval.
serverStatus.dur.compression
New in version 2.0.
The compression (page 379) represents the compression ratio of the data written to the journal:
( journaled_size_of_data / uncompressed_size_of_data )
serverStatus.dur.commitsInWriteLock
The commitsInWriteLock (page 379) provides a count of the commits that occurred while a write lock was
held. Commits in a write lock indicate a MongoDB node under a heavy write load and call for further diagnosis.
2.2. Database Commands
379
MongoDB Reference Manual, Release 2.8.0-rc3
serverStatus.dur.earlyCommits
The earlyCommits (page 379) value reflects the number of times MongoDB requested a commit before the
scheduled journal group commit interval. Use this value to ensure that your journal group commit interval is
not too long for your deployment.
serverStatus.dur.timeMS
The timeMS (page 380) document provides information about the performance of the mongod (page 583)
instance during the various phases of journaling in the last journal group commit interval.
serverStatus.dur.timeMS.dt
The dt (page 380) value provides, in milliseconds, the amount of time over which MongoDB collected the
timeMS (page 380) data. Use this field to provide context to the other timeMS (page 380) field values.
serverStatus.dur.timeMS.prepLogBuffer
The prepLogBuffer (page 380) value provides, in milliseconds, the amount of time spent preparing to write
to the journal. Smaller values indicate better journal performance.
serverStatus.dur.timeMS.writeToJournal
The writeToJournal (page 380) value provides, in milliseconds, the amount of time spent actually writing
to the journal. File system speeds and device interfaces can affect performance.
serverStatus.dur.timeMS.writeToDataFiles
The writeToDataFiles (page 380) value provides, in milliseconds, the amount of time spent writing to
data files after journaling. File system speeds and device interfaces can affect performance.
serverStatus.dur.timeMS.remapPrivateView
The remapPrivateView (page 380) value provides, in milliseconds, the amount of time spent remapping
copy-on-write memory mapped views. Smaller values indicate better journal performance.
recordStats For an example of the recordStats output, see the recordStats section of the
http://docs.mongodb.org/manual/reference/server-status page.
serverStatus.recordStats
The recordStats (page 380) document provides fine grained reporting on page faults on a per database level.
MongoDB uses a read lock on each database to return recordStats (page 380). To minimize this overhead,
you can disable this section, as in the following operation:
db.serverStatus( { recordStats: 0 } )
serverStatus.recordStats.accessesNotInMemory
accessesNotInMemory (page 380) reflects the number of times mongod (page 583) needed to access a
memory page that was not resident in memory for all databases managed by this mongod (page 583) instance.
serverStatus.recordStats.pageFaultExceptionsThrown
pageFaultExceptionsThrown (page 380) reflects the number of page fault exceptions thrown by
mongod (page 583) when accessing data for all databases managed by this mongod (page 583) instance.
serverStatus.recordStats.local.accessesNotInMemory
accessesNotInMemory (page 380) reflects the number of times mongod (page 583) needed to access a
memory page that was not resident in memory for the local database.
serverStatus.recordStats.local.pageFaultExceptionsThrown
pageFaultExceptionsThrown (page 380) reflects the number of page fault exceptions thrown by
mongod (page 583) when accessing data for the local database.
serverStatus.recordStats.admin.accessesNotInMemory
accessesNotInMemory (page 380) reflects the number of times mongod (page 583) needed to access a
memory page that was not resident in memory for the admin database.
380
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
serverStatus.recordStats.admin.pageFaultExceptionsThrown
pageFaultExceptionsThrown (page 380) reflects the number of page fault exceptions thrown by
mongod (page 583) when accessing data for the admin database.
serverStatus.recordStats.<database>.accessesNotInMemory
accessesNotInMemory (page 381) reflects the number of times mongod (page 583) needed to access a
memory page that was not resident in memory for the <database> database.
serverStatus.recordStats.<database>.pageFaultExceptionsThrown
pageFaultExceptionsThrown (page 381) reflects the number of page fault exceptions thrown by
mongod (page 583) when accessing data for the <database> database.
workingSet New in version 2.4.
Note: The workingSet (page 381) data is only included in the output of serverStatus (page 366) if explicitly
enabled. To return the workingSet (page 381), use one of the following commands:
db.serverStatus( { workingSet: 1 } )
db.runCommand( { serverStatus: 1, workingSet: 1 } )
For
an
example
of
the
workingSet
output,
see
the
workingSet
http://docs.mongodb.org/manual/reference/server-status page.
section
of
the
serverStatus.workingSet
workingSet (page 381) is a document that contains values useful for estimating the size of the working set,
which is the amount of data that MongoDB uses actively. workingSet (page 381) uses an internal data
structure that tracks pages accessed by mongod (page 583).
serverStatus.workingSet.note
note (page 381) is a field that holds a string warning that the workingSet (page 381) document is an
estimate.
serverStatus.workingSet.pagesInMemory
pagesInMemory (page 381) contains a count of the total number of pages accessed by mongod (page 583)
over the period displayed in overSeconds (page 381). The default page size is 4 kilobytes: to convert this
value to the amount of data in memory multiply this value by 4 kilobytes.
If your total working set is less than the size of physical memory, over time the value of pagesInMemory
(page 381) will reflect your data size.
Use pagesInMemory (page 381) in conjunction with overSeconds (page 381) to help estimate the actual
size of the working set.
serverStatus.workingSet.computationTimeMicros
computationTimeMicros (page 381) reports the amount of time the mongod (page 583) instance used to
compute the other fields in the workingSet (page 381) section.
Reporting on workingSet (page 381) may impact the performance of other operations on the mongod
(page 583) instance because MongoDB must collect some data within the context of a lock. Ensure that automated monitoring tools consider this metric when determining the frequency of collection for workingSet
(page 381).
serverStatus.workingSet.overSeconds
overSeconds (page 381) returns the amount of time elapsed between the newest and oldest pages tracked in
the pagesInMemory (page 381) data point.
If overSeconds (page 381) is decreasing, or if pagesInMemory (page 381) equals physical RAM and
overSeconds (page 381) is very small, the working set may be much larger than physical RAM.
2.2. Database Commands
381
MongoDB Reference Manual, Release 2.8.0-rc3
When overSeconds (page 381) is large, MongoDB’s data set is equal to or smaller than physical RAM.
metrics For
an
example
of
the
metrics
output,
see
the
metrics
http://docs.mongodb.org/manual/reference/server-status page.
section
of
the
New in version 2.4.0.
serverStatus.metrics
The metrics (page 382) document holds a number of statistics that reflect the current use and state of a
running mongod (page 583) instance.
serverStatus.metrics.commands
New in version 2.8.0.
A document that reports on the use of database commands. The fields in commands (page 382) are the names
of database commands (page 210) and each value is a document that reports the total number of commands
executed as well as the number of failed executions.
serverStatus.metrics.commands.<command>.failed
The number of times <command> failed on this mongod (page 583).
serverStatus.metrics.commands.<command>.total
The number of times <command> executed on this mongod (page 583).
serverStatus.metrics.document
The document (page 382) holds a document of that reflect document access and modification patterns and data
use. Compare these values to the data in the opcounters (page 376) document, which track total number of
operations.
serverStatus.metrics.document.deleted
deleted (page 382) reports the total number of documents deleted.
serverStatus.metrics.document.inserted
inserted (page 382) reports the total number of documents inserted.
serverStatus.metrics.document.returned
returned (page 382) reports the total number of documents returned by queries.
serverStatus.metrics.document.updated
updated (page 382) reports the total number of documents updated.
serverStatus.metrics.getLastError
getLastError (page 382) is a document that reports on getLastError (page 245) use.
serverStatus.metrics.getLastError.wtime
wtime (page 382) is a sub-document that reports getLastError (page 245) operation counts with a w
argument greater than 1.
serverStatus.metrics.getLastError.wtime.num
num (page 382) reports the total number of getLastError (page 245) operations with a specified write
concern (i.e. w) that wait for one or more members of a replica set to acknowledge the write operation (i.e. a w
value greater than 1.)
serverStatus.metrics.getLastError.wtime.totalMillis
totalMillis (page 382) reports the total amount of time in milliseconds that the mongod (page 583) has
spent performing getLastError (page 245) operations with write concern (i.e. w) that wait for one or more
members of a replica set to acknowledge the write operation (i.e. a w value greater than 1.)
serverStatus.metrics.getLastError.wtimeouts
wtimeouts (page 382) reports the number of times that write concern operations have timed out as a result of
the wtimeout threshold to getLastError (page 245).
382
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
serverStatus.metrics.operation
operation (page 382) is a sub-document that holds counters for several types of update and query operations
that MongoDB handles using special operation types.
serverStatus.metrics.operation.fastmod
fastmod (page 383) reports the number of update operations that neither cause documents to grow nor
require updates to the index. For example, this counter would record an update operation that use the $inc
(page 452) operator to increment the value of a field that is not indexed.
serverStatus.metrics.operation.idhack
idhack (page 383) reports the number of queries that contain the _id field. For these queries, MongoDB will
use default index on the _id field and skip all query plan analysis.
serverStatus.metrics.operation.scanAndOrder
scanAndOrder (page 383) reports the total number of queries that return sorted numbers that cannot perform
the sort operation using an index.
serverStatus.metrics.queryExecutor
queryExecutor (page 383) is a document that reports data from the query execution system.
serverStatus.metrics.queryExecutor.scanned
scanned (page 383) reports the total number of index items scanned during queries and query-plan evaluation.
This counter is the same as nscanned (page ??) in the output of explain() (page 85).
serverStatus.metrics.record
record (page 383) is a document that reports data related to record allocation in the on-disk memory files.
serverStatus.metrics.record.moves
moves (page 383) reports the total number of times documents move within the on-disk representation of the
MongoDB data set. Documents move as a result of operations that increase the size of the document beyond
their allocated record size.
serverStatus.metrics.repl
repl (page 383) holds a sub-document that reports metrics related to the replication process. repl (page 383)
document appears on all mongod (page 583) instances, even those that aren’t members of replica sets.
serverStatus.metrics.repl.apply
apply (page 383) holds a sub-document that reports on the application of operations from the replication oplog.
serverStatus.metrics.repl.apply.batches
batches (page 383) reports on the oplog application process on secondaries members of replica sets. See
replica-set-internals-multi-threaded-replication for more information on the oplog application processes
serverStatus.metrics.repl.apply.batches.num
num (page 383) reports the total number of batches applied across all databases.
serverStatus.metrics.repl.apply.batches.totalMillis
totalMillis (page 383) reports the total amount of time the mongod (page 583) has spent applying operations from the oplog.
serverStatus.metrics.repl.apply.ops
ops (page 383) reports the total number of oplog operations applied.
serverStatus.metrics.repl.buffer
MongoDB buffers oplog operations from the replication sync source buffer before applying oplog entries in a
batch. buffer (page 383) provides a way to track the oplog buffer. See replica-set-internals-multi-threadedreplication for more information on the oplog application process.
serverStatus.metrics.repl.buffer.count
count (page 383) reports the current number of operations in the oplog buffer.
2.2. Database Commands
383
MongoDB Reference Manual, Release 2.8.0-rc3
serverStatus.metrics.repl.buffer.maxSizeBytes
maxSizeBytes (page 383) reports the maximum size of the buffer. This value is a constant setting in the
mongod (page 583), and is not configurable.
serverStatus.metrics.repl.buffer.sizeBytes
sizeBytes (page 384) reports the current size of the contents of the oplog buffer.
serverStatus.metrics.repl.network
network (page 384) reports network use by the replication process.
serverStatus.metrics.repl.network.bytes
bytes (page 384) reports the total amount of data read from the replication sync source.
serverStatus.metrics.repl.network.getmores
getmores (page 384) reports on the getmore operations, which are requests for additional results from the
oplog cursor as part of the oplog replication process.
serverStatus.metrics.repl.network.getmores.num
num (page 384) reports the total number of getmore operations, which are operations that request an additional
set of operations from the replication sync source.
serverStatus.metrics.repl.network.getmores.totalMillis
totalMillis (page 384) reports the total amount of time required to collect data from getmore operations.
Note: This number can be quite large, as MongoDB will wait for more data even if the getmore operation
does not initial return data.
serverStatus.metrics.repl.network.ops
ops (page 384) reports the total number of operations read from the replication source.
serverStatus.metrics.repl.network.readersCreated
readersCreated (page 384) reports the total number of oplog query processes created. MongoDB will
create a new oplog query any time an error occurs in the connection, including a timeout, or a network operation.
Furthermore, readersCreated (page 384) will increment every time MongoDB selects a new source fore
replication.
serverStatus.metrics.repl.oplog
oplog (page 384) is a document that reports on the size and use of the oplog by this mongod (page 583)
instance.
serverStatus.metrics.repl.oplog.insert
insert (page 384) is a document that reports insert operations into the oplog.
serverStatus.metrics.repl.oplog.insert.num
num (page 384) reports the total number of items inserted into the oplog.
serverStatus.metrics.repl.oplog.insert.totalMillis
totalMillis (page 384) reports the total amount of time spent for the mongod (page 583) to insert data into
the oplog.
serverStatus.metrics.repl.oplog.insertBytes
insertBytes (page 384) the total size of documents inserted into the oplog.
serverStatus.metrics.repl.preload
preload (page 384) reports on the “pre-fetch” stage, where MongoDB loads documents and indexes into
RAM to improve replication throughput.
See replica-set-internals-multi-threaded-replication for more information about the pre-fetch stage of the replication process.
384
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
serverStatus.metrics.repl.preload.docs
docs (page 384) is a sub-document that reports on the documents loaded into memory during the pre-fetch
stage.
serverStatus.metrics.repl.preload.docs.num
num (page 385) reports the total number of documents loaded during the pre-fetch stage of replication.
serverStatus.metrics.repl.preload.docs.totalMillis
totalMillis (page 385) reports the total amount of time spent loading documents as part of the pre-fetch
stage of replication.
serverStatus.metrics.repl.preload.indexes
indexes (page 385) is a sub-document that reports on the index items loaded into memory during the pre-fetch
stage of replication.
See replica-set-internals-multi-threaded-replication for more information about the pre-fetch stage of replication.
serverStatus.metrics.repl.preload.indexes.num
num (page 385) reports the total number of index entries loaded by members before updating documents as part
of the pre-fetch stage of replication.
serverStatus.metrics.repl.preload.indexes.totalMillis
totalMillis (page 385) reports the total amount of time spent loading index entries as part of the pre-fetch
stage of replication.
serverStatus.storage.freelist.search.bucketExhausted
bucketExhausted (page 385) reports the number of times that mongod (page 583) has checked the free list
without finding a suitably large record allocation.
serverStatus.storage.freelist.search.requests
requests (page 385) reports the number of times mongod (page 583) has searched for available record
allocations.
serverStatus.storage.freelist.search.scanned
scanned (page 385) reports the number of available record allocations mongod (page 583) has searched.
serverStatus.metrics.ttl
ttl (page 385) is a sub-document that reports on the operation of the resource use of the ttl index process.
serverStatus.metrics.ttl.deletedDocuments
deletedDocuments (page 385) reports the total number of documents deleted from collections with a ttl
index.
serverStatus.metrics.ttl.passes
passes (page 385) reports the number of times the background process removes documents from collections
with a ttl index.
serverStatus.metrics.cursor
New in version 2.6.
The cursor (page 385) is a document that contains data regarding cursor state and use.
serverStatus.metrics.cursor.timedOut
New in version 2.6.
timedOut (page 385) provides the total number of cursors that have timed out since the server process started.
If this number is large or growing at a regular rate, this may indicate an application error.
serverStatus.metrics.cursor.open
New in version 2.6.
The open (page 385) is an embedded document that contains data regarding open cursors.
2.2. Database Commands
385
MongoDB Reference Manual, Release 2.8.0-rc3
serverStatus.metrics.cursor.open.noTimeout
New in version 2.6.
noTimeout (page 385) provides the number of open cursors with
DBQuery.Option.noTimeout (page 82) set to prevent timeout after a period of inactivity.
the
option
serverStatus.metrics.cursor.open.pinned
New in version 2.6.
serverStatus.metrics.cursor.open.pinned (page 386) provides the number of “pinned” open
cursors.
serverStatus.metrics.cursor.open.total
New in version 2.6.
total (page 386) provides the number of cursors that MongoDB is maintaining for clients. Because MongoDB
exhausts unused cursors, typically this value small or zero. However, if there is a queue, stale tailable cursors,
or a large number of operations this value may rise.
shardConnPoolStats
Definition
shardConnPoolStats
Returns information on the pooled and cached connections in the sharded connection pool. The command also
returns information on the per-thread connection cache in the connection pool.
The shardConnPoolStats (page 386) command uses the following syntax:
{ shardConnPoolStats: 1 }
The sharded connection pool is specific to connections between members in a sharded cluster. The mongos
(page 601) instances in a cluster use the connection pool to execute client reads and writes. The mongod
(page 583) instances in a cluster use the pool when issuing mapReduce (page 220) to query temporary collections on other shards.
When the cluster requires a connection, MongoDB pulls a connection from the sharded connection pool into the
per-thread connection cache. MongoDB returns the connection to the connection pool after every operation.
Output
shardConnPoolStats.hosts
Displays connection status for each config server, replica set, and standalone instance in the cluster.
shardConnPoolStats.hosts.<host>.available
The number of connections available for this host to connect to the mongos (page 601).
shardConnPoolStats.hosts.<host>.created
The number of connections the host has ever created to connect to the mongos (page 601).
shardConnPoolStats.replicaSets
Displays information specific to replica sets.
shardConnPoolStats.replicaSets.<name>.host
Holds an array of documents that report on each replica set member. These values derive from the replica
set status (page 296) values.
shardConnPoolStats.replicaSets.<name>.host[n].addr
The host address in the format [hostname]:[port].
386
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
shardConnPoolStats.replicaSets.<name>.host[n].ok
This field is for internal use. Reports false when the mongos (page 601) either cannot connect to
instance or received a connection exception or error.
shardConnPoolStats.replicaSets.<name>.host[n].ismaster
The host is the replica set’s primary if this is set to true.
shardConnPoolStats.replicaSets.<name>.host[n].hidden
The host is a hidden member of the replica set if this is set to true.
shardConnPoolStats.replicaSets.<name>.host[n].secondary
The host is a hidden member of the replica set if this is set to true.
The host is a secondary member of the replica set if this is set to true.
shardConnPoolStats.replicaSets.<name>.host[n].pingTimeMillis
The latency, in milliseconds, from the mongos (page 601) to this member.
shardConnPoolStats.replicaSets.<name>.host[n].tags
The member has tags configured.
shardConnPoolStats.createdByType
The number connections in the cluster’s connection pool.
shardConnPoolStats.createdByType.master
The number of connections to a shard.
shardConnPoolStats.createdByType.set
The number of connections to a replica set.
shardConnPoolStats.createdByType.sync
The number of connections to the config database.
shardConnPoolStats.totalAvailable
The number of connections available from the mongos (page 601) to the config servers, replica sets, and
standalone mongod (page 583) instances in the cluster.
shardConnPoolStats.totalCreated
The number of connections the mongos (page 601) has ever created to other members of the cluster.
shardConnPoolStats.threads
Displays information on the per-thread connection cache.
shardConnPoolStats.threads.hosts
Displays each incoming client connection. For a mongos (page 601), this array field displays one document per incoming client thread. For a mongod (page 583), the array displays one entry per incoming
sharded mapReduce (page 220) client thread.
shardConnPoolStats.threads.hosts.host
The host using the connection. The host can be a config server, replica set, or standalone instance.
shardConnPoolStats.threads.hosts.created
The number of times the host pulled a connection from the pool.
shardConnPoolStats.threads.hosts.avail
The thread’s availability.
shardConnPoolStats.threads.seenNS
The namespaces used on this connection thus far.
top
2.2. Database Commands
387
MongoDB Reference Manual, Release 2.8.0-rc3
top
top (page 387) is an administrative command that returns usage statistics for each collection. top (page 387)
provides amount of time, in microseconds, used and a count of operations for the following event types:
•total
•readLock
•writeLock
•queries
•getmore
•insert
•update
•remove
•commands
Issue the top (page 387) command against the admin database in the form:
{ top: 1 }
Example At the mongo (page 610) shell prompt, use top (page 387) with the following evocation:
db.adminCommand("top")
Alternately you can use top (page 387) as follows:
use admin
db.runCommand( { top: 1 } )
The output of the top command would resemble the following output:
{
"totals" : {
"records.users" : {
"total" : {
"time" : 305277,
"count" : 2825
},
"readLock" : {
"time" : 305264,
"count" : 2824
},
"writeLock" : {
"time" : 13,
"count" : 1
},
"queries" : {
"time" : 305264,
"count" : 2824
},
"getmore" : {
"time" : 0,
"count" : 0
},
"insert" : {
"time" : 0,
388
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
"count" : 0
},
"update" : {
"time" : 0,
"count" : 0
},
"remove" : {
"time" : 0,
"count" : 0
},
"commands" : {
"time" : 0,
"count" : 0
}
}
}
validate
Definition
validate
The validate (page 389) command checks the structures within a namespace for correctness by scanning
the collection’s data and indexes. The command returns information regarding the on-disk representation of the
collection.
The validate command can be slow, particularly on larger data sets.
The following example validates the contents of the collection named users.
{ validate: "users" }
You may also specify one of the following options:
•full:
true provides a more thorough scan of the data.
•scandata:
false skips the scan of the base collection without skipping the scan of the index.
The mongo (page 610) shell also provides a wrapper:
db.collection.validate();
Use one of the following forms to perform the full collection validation:
db.collection.validate(true)
db.runCommand( { validate: "collection", full: true } )
Warning: This command is resource intensive and may have an impact on the performance of your MongoDB instance.
Output
validate.ns
The full namespace name of the collection. Namespaces include the database name and the collection name in
the form database.collection.
validate.firstExtent
The disk location of the first extent in the collection. The value of this field also includes the namespace.
2.2. Database Commands
389
MongoDB Reference Manual, Release 2.8.0-rc3
validate.lastExtent
The disk location of the last extent in the collection. The value of this field also includes the namespace.
validate.extentCount
The number of extents in the collection.
validate.extents
validate (page 389) returns one instance of this document for every extent in the collection. This subdocument is only returned when you specify the full option to the command.
validate.extents.loc
The disk location for the beginning of this extent.
validate.extents.xnext
The disk location for the extent following this one. “null” if this is the end of the linked list of extents.
validate.extents.xprev
The disk location for the extent preceding this one. “null” if this is the head of the linked list of extents.
validate.extents.nsdiag
The namespace this extent belongs to (should be the same as the namespace shown at the beginning of the
validate listing).
validate.extents.size
The number of bytes in this extent.
validate.extents.firstRecord
The disk location of the first record in this extent.
validate.extents.lastRecord
The disk location of the last record in this extent.
validate.datasize
The number of bytes in all data records. This value does not include deleted records, nor does it include extent
headers, nor record headers, nor space in a file unallocated to any extent. datasize (page 390) includes record
padding.
validate.nrecords
The number of documents in the collection.
validate.lastExtentSize
The size of the last new extent created in this collection. This value determines the size of the next extent created.
validate.padding
A floating point value between 1 and 2.
When MongoDB creates a new record it uses the padding factor to determine how much additional space to add
to the record. The padding factor is automatically adjusted by mongo when it notices that update operations are
triggering record moves.
validate.firstExtentDetails
The size of the first extent created in this collection. This data is similar to the data provided by the extents
(page 390) sub-document; however, the data reflects only the first extent in the collection and is always returned.
validate.firstExtentDetails.loc
The disk location for the beginning of this extent.
validate.firstExtentDetails.xnext
The disk location for the extent following this one. “null” if this is the end of the linked list of extents,
which should only be the case if there is only one extent.
390
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
validate.firstExtentDetails.xprev
The disk location for the extent preceding this one. This should always be “null.”
validate.firstExtentDetails.nsdiag
The namespace this extent belongs to (should be the same as the namespace shown at the beginning of the
validate listing).
validate.firstExtentDetails.size
The number of bytes in this extent.
validate.firstExtentDetails.firstRecord
The disk location of the first record in this extent.
validate.firstExtentDetails.lastRecord
The disk location of the last record in this extent.
validate.objectsFound
The number of records actually encountered in a scan of the collection. This field should have the same value
as the nrecords (page 390) field.
validate.invalidObjects
The number of records containing BSON documents that do not pass a validation check.
Note: This field is only included in the validation output when you specify the full option.
validate.bytesWithHeaders
This is similar to datasize, except that bytesWithHeaders (page 391) includes the record headers. In version
2.0, record headers are 16 bytes per document.
Note: This field is only included in the validation output when you specify the full option.
validate.bytesWithoutHeaders
bytesWithoutHeaders (page 391) returns data collected from a scan of all records. The value should be
the same as datasize (page 390).
Note: This field is only included in the validation output when you specify the full option.
validate.deletedCount
The number of deleted or “free” records in the collection.
validate.deletedSize
The size of all deleted or “free” records in the collection.
validate.nIndexes
The number of indexes on the data in the collection.
validate.keysPerIndex
A document containing a field for each index, named after the index’s name, that contains the number of keys,
or documents referenced, included in the index.
validate.valid
Boolean. true, unless validate (page 389) determines that an aspect of the collection is not valid. When
false, see the errors (page 391) field for more information.
validate.errors
Typically empty; however, if the collection is not valid (i.e valid (page 391) is false), this field will contain a
message describing the validation error.
2.2. Database Commands
391
MongoDB Reference Manual, Release 2.8.0-rc3
validate.ok
Set to 1 when the command succeeds. If the command fails the ok (page 391) field has a value of 0.
whatsmyuri
whatsmyuri
whatsmyuri (page 392) is an internal command.
2.2.3 Internal Commands
Internal Commands
Name
_migrateClone (page 392)
_recvChunkAbort (page 392)
_recvChunkCommit
(page 392)
_recvChunkStart (page 393)
_recvChunkStatus
(page 393)
_replSetFresh
_transferMods (page 393)
handshake (page 393)
mapreduce.shardedfinish
(page 393)
replSetElect (page 393)
replSetGetRBID (page 393)
replSetHeartbeat
(page 394)
writeBacksQueued
(page 394)
writebacklisten (page 395)
Description
Internal command that supports chunk migration. Do not call directly.
Internal command that supports chunk migrations in sharded clusters. Do not
call directly.
Internal command that supports chunk migrations in sharded clusters. Do not
call directly.
Internal command that facilitates chunk migrations in sharded clusters.. Do
not call directly.
Internal command that returns data to support chunk migrations in sharded
clusters. Do not call directly.
Internal command that supports replica set election operations.
Internal command that supports chunk migrations. Do not call directly.
Internal command.
Internal command that supports map-reduce in sharded cluster
environments.
Internal command that supports replica set functionality.
Internal command that supports replica set operations.
Internal command that supports replica set operations.
Internal command that supports chunk migrations in sharded clusters.
Internal command that supports chunk migrations in sharded clusters.
migrateClone
_migrateClone
_migrateClone (page 392) is an internal command. Do not call directly.
recvChunkAbort
_recvChunkAbort
_recvChunkAbort (page 392) is an internal command. Do not call directly.
recvChunkCommit
_recvChunkCommit
_recvChunkCommit (page 392) is an internal command. Do not call directly.
392
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
recvChunkStart
_recvChunkStart
_recvChunkStart (page 393) is an internal command. Do not call directly.
Warning: This command obtains a write lock on the affected database and will block other operations until
it has completed.
recvChunkStatus
_recvChunkStatus
_recvChunkStatus (page 393) is an internal command. Do not call directly.
replSetFresh
replSetFresh
replSetFresh (page 393) is an internal command that supports replica set functionality.
transferMods
_transferMods
_transferMods (page 393) is an internal command. Do not call directly.
handshake
handshake
handshake (page 393) is an internal command.
mapreduce.shardedfinish
mapreduce.shardedfinish
Provides internal functionality to support map-reduce in sharded environments.
See also:
“mapReduce (page 220)“
replSetElect
replSetElect
replSetElect (page 393) is an internal command that support replica set functionality.
replSetGetRBID
replSetGetRBID
replSetGetRBID (page 393) is an internal command that supports replica set functionality.
2.2. Database Commands
393
MongoDB Reference Manual, Release 2.8.0-rc3
replSetHeartbeat
replSetHeartbeat
replSetHeartbeat (page 394) is an internal command that supports replica set functionality.
writeBacksQueued
writeBacksQueued
writeBacksQueued (page 394) is an internal command that returns a document reporting there are operations in the write back queue for the given mongos (page 601) and information about the queues.
writeBacksQueued.hasOpsQueued
Boolean.
hasOpsQueued (page 394) is true if there are write Back operations queued.
writeBacksQueued.totalOpsQueued
Integer.
totalOpsQueued (page 394) reflects the number of operations queued.
writeBacksQueued.queues
Document.
queues (page 394) holds a sub-document where the fields are all write back queues. These field hold a
document with two fields that reports on the state of the queue. The fields in these documents are:
writeBacksQueued.queues.n
n (page 394) reflects the size, by number of items, in the queues.
writeBacksQueued.queues.minutesSinceLastCall
The number of minutes since the last time the mongos (page 601) touched this queue.
The command document has the following prototype form:
{writeBacksQueued: 1}
To call writeBacksQueued (page 394) from the mongo (page 610) shell, use the following
db.runCommand() (page 123) form:
db.runCommand({writeBacksQueued: 1})
Consider the following example output:
{
"hasOpsQueued" : true,
"totalOpsQueued" : 7,
"queues" : {
"50b4f09f6671b11ff1944089"
"50b4f09fc332bf1c5aeaaf59"
"50b4f09f6671b1d51df98cb6"
"50b4f0c67ccf1e5c6effb72e"
"50b4faf12319f193cfdec0d1"
"50b4f013d2c1f8d62453017e"
"50b4f0f12319f193cfdec0d1"
},
"ok" : 1
:
:
:
:
:
:
:
{
{
{
{
{
{
{
"n"
"n"
"n"
"n"
"n"
"n"
"n"
:
:
:
:
:
:
:
0,
0,
0,
0,
0,
0,
0,
"minutesSinceLastCall"
"minutesSinceLastCall"
"minutesSinceLastCall"
"minutesSinceLastCall"
"minutesSinceLastCall"
"minutesSinceLastCall"
"minutesSinceLastCall"
:
:
:
:
:
:
:
1
0
0
0
4
0
1
},
},
},
},
},
},
}
}
394
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
writebacklisten
writebacklisten
writebacklisten (page 395) is an internal command.
2.2.4 Testing Commands
Testing Commands
Name
_hashBSONElement
(page 395)
_journalLatencyTest
Description
Internal command. Computes the MD5 hash of a BSON element.
Tests the time required to write and perform a file system sync for a file in the
journal directory.
Internal command. Truncates capped collections.
Internal command for testing. Configures failure points.
captrunc (page 397)
configureFailPoint
(page 397)
emptycapped (page 398)
Internal command. Removes all documents from a capped collection.
forceerror (page 398)
Internal command for testing. Forces a user assertion exception.
godinsert (page 398)
Internal command for testing.
replSetTest (page 398)
Internal command for testing replica set functionality.
skewClockCommand
Internal command. Do not call this command directly.
sleep (page 399)
Internal command for testing. Forces MongoDB to block all operations.
testDistLockWithSkew
Internal command. Do not call this directly.
testDistLockWithSyncCluster
Internal command. Do not call this directly.
_hashBSONElement
Description
_hashBSONElement
New in version 2.4.
An internal command that computes the MD5 hash of a BSON element. The _hashBSONElement (page 395)
command returns 8 bytes from the 16 byte MD5 hash.
The _hashBSONElement (page 395) command has the following form:
db.runCommand({ _hashBSONElement: <key> , seed: <seed> })
The _hashBSONElement (page 395) command has the following fields:
field BSONElement key The BSON element to hash.
field integer seed A seed used when computing the hash.
Note:
_hashBSONElement (page 395) is an internal command that is not enabled by
default.
_hashBSONElement (page 395) must be enabled by using --setParameter
enableTestCommands=1 on the mongod (page 583) command line. _hashBSONElement (page 395)
cannot be enabled during run-time.
Output The _hashBSONElement (page 395) command returns a document that holds the following fields:
2.2. Database Commands
395
MongoDB Reference Manual, Release 2.8.0-rc3
_hashBSONElement.key
The original BSON element.
_hashBSONElement.seed
The seed used for the hash, defaults to 0.
_hashBSONElement.out
The decimal result of the hash.
_hashBSONElement.ok
Holds the 1 if the function returns successfully, and 0 if the operation encountered an error.
Example Invoke a mongod (page 583) instance with test commands enabled:
mongod --setParameter enableTestCommands=1
Run the following to compute the hash of an ISODate string:
db.runCommand({_hashBSONElement: ISODate("2013-02-12T22:12:57.211Z")})
The command returns the following document:
{
"key" : ISODate("2013-02-12T22:12:57.211Z"),
"seed" : 0,
"out" : NumberLong("-4185544074338741873"),
"ok" : 1
}
Run the following to hash the same ISODate string but this time to specify a seed value:
db.runCommand({_hashBSONElement: ISODate("2013-02-12T22:12:57.211Z"), seed:2013})
The command returns the following document:
{
"key" : ISODate("2013-02-12T22:12:57.211Z"),
"seed" : 2013,
"out" : NumberLong("7845924651247493302"),
"ok" : 1
}
journalLatencyTest
journalLatencyTest
journalLatencyTest (page 396) is an administrative command that tests the length of time required
to write and perform a file system sync (e.g. fsync) for a file in the journal directory. You must issue the
journalLatencyTest (page 396) command against the admin database in the form:
{ journalLatencyTest: 1 }
The value (i.e. 1 above), does not affect the operation of the command.
Note:
journalLatencyTest (page 396) is an internal command that is not enabled by
default.
journalLatencyTest (page 396) must be enabled by using --setParameter
enableTestCommands=1 on the mongod (page 583) command line. journalLatencyTest (page 396)
cannot be enabled during run-time.
396
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
captrunc
Definition
captrunc
captrunc (page 397) is a command that truncates capped collections for diagnostic and testing purposes and
is not part of the stable client facing API. The command takes the following form:
{ captrunc: "<collection>", n: <integer>, inc: <true|false> }.
captrunc (page 397) has the following fields:
field string captrunc The name of the collection to truncate.
field integer n The number of documents to remove from the collection.
field boolean inc Specifies whether to truncate the nth document.
Note: captrunc (page 397) is an internal command that is not enabled by default. captrunc (page 397) must
be enabled by using --setParameter enableTestCommands=1 on the mongod (page 583) command line.
captrunc (page 397) cannot be enabled during run-time.
Examples The following command truncates 10 older documents from the collection records:
db.runCommand({captrunc: "records" , n: 10})
The following command truncates 100 documents and the 101st document:
db.runCommand({captrunc: "records", n: 100, inc: true})
configureFailPoint
Definition
configureFailPoint
Configures a failure point that you can turn on and off while MongoDB runs. configureFailPoint
(page 397) is an internal command for testing purposes that takes the following form:
{configureFailPoint: "<failure_point>", mode: <behavior> }
You must issue configureFailPoint (page 397) against the admin database. configureFailPoint
(page 397) has the following fields:
field string configureFailPoint The name of the failure point.
field document,string mode Controls the behavior of a failure point. The possible values are
alwaysOn, off, or a document in the form of {times: n} that specifies the number of
times the failure point remains on before it deactivates. The maximum value for the number is a
32-bit signed integer.
field document data Passes in additional data for use in configuring the fail point. For example, to
imitate a slow connection pass in a document that contains a delay time.
Note:
configureFailPoint (page 397) is an internal command that is not enabled by default.
configureFailPoint (page 397) must be enabled by using --setParameter enableTestCommands=1
on the mongod (page 583) command line. configureFailPoint (page 397) cannot be enabled during run-time.
2.2. Database Commands
397
MongoDB Reference Manual, Release 2.8.0-rc3
Example
db.adminCommand( { configureFailPoint: "blocking_thread", mode: {times: 21} } )
emptycapped
emptycapped
The emptycapped command removes all documents from a capped collection. Use the following syntax:
{ emptycapped: "events" }
This command removes all records from the capped collection named events.
Warning: This command obtains a write lock on the affected database and will block other operations until
it has completed.
Note: emptycapped (page 398) is an internal command that is not enabled by default. emptycapped
(page 398) must be enabled by using --setParameter enableTestCommands=1 on the mongod
(page 583) command line. emptycapped (page 398) cannot be enabled during run-time.
forceerror
forceerror
The forceerror (page 398) command is for testing purposes only. Use forceerror (page 398) to force a
user assertion exception. This command always returns an ok value of 0.
godinsert
godinsert
godinsert (page 398) is an internal command for testing purposes only.
Note: This command obtains a write lock on the affected database and will block other operations until it has
completed.
Note: godinsert (page 398) is an internal command that is not enabled by default. godinsert (page 398)
must be enabled by using --setParameter enableTestCommands=1 on the mongod (page 583) command line. godinsert (page 398) cannot be enabled during run-time.
replSetTest
replSetTest
replSetTest (page 398) is internal diagnostic command used for regression tests that supports replica set
functionality.
Note: replSetTest (page 398) is an internal command that is not enabled by default. replSetTest
(page 398) must be enabled by using --setParameter enableTestCommands=1 on the mongod
(page 583) command line. replSetTest (page 398) cannot be enabled during run-time.
398
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
skewClockCommand
_skewClockCommand
_skewClockCommand (page 399) is an internal command. Do not call directly.
Note:
_skewClockCommand (page 399) is an internal command that is not enabled by
default.
_skewClockCommand (page 399) must be enabled by using --setParameter
enableTestCommands=1 on the mongod (page 583) command line. _skewClockCommand (page 399)
cannot be enabled during run-time.
sleep
Definition
sleep
Forces the database to block all operations. This is an internal command for testing purposes.
The sleep (page 399) command takes the following prototype form:
{ sleep: 1, w: <true|false>, secs: <seconds> }
The sleep (page 399) command has the following fields:
field boolean w If true, obtains a global write lock. Otherwise obtains a read lock.
field integer secs The number of seconds to sleep.
Behavior The command places the mongod (page 583) instance in a write lock state for 100 seconds. Without
arguments, sleep (page 399) causes a “read lock” for 100 seconds.
Warning: sleep (page 399) claims the lock specified in the w argument and blocks all operations on the mongod
(page 583) instance for the specified amount of time.
Note: sleep (page 399) is an internal command that is not enabled by default. sleep (page 399) must be enabled
by using --setParameter enableTestCommands=1 on the mongod (page 583) command line. sleep
(page 399) cannot be enabled during run-time.
testDistLockWithSkew
_testDistLockWithSkew
_testDistLockWithSkew (page 399) is an internal command. Do not call directly.
Note:
_testDistLockWithSkew (page 399) is an internal command that is not enabled by
default.
_testDistLockWithSkew (page 399) must be enabled by using --setParameter
enableTestCommands=1 on the mongod (page 583) command line. _testDistLockWithSkew
(page 399) cannot be enabled during run-time.
testDistLockWithSyncCluster
_testDistLockWithSyncCluster
_testDistLockWithSyncCluster (page 399) is an internal command. Do not call directly.
2.2. Database Commands
399
MongoDB Reference Manual, Release 2.8.0-rc3
Note:
_testDistLockWithSyncCluster (page 399) is an internal command that is not
enabled by default.
_testDistLockWithSyncCluster (page 399) must be enabled by using --setParameter enableTestCommands=1 on the mongod (page 583) command line.
_testDistLockWithSyncCluster (page 399) cannot be enabled during run-time.
2.2.5 Auditing Commands
System Events Auditing Commands
Name
logApplicationMessage (page 400)
Description
Posts a custom message to the audit log.
logApplicationMessage
logApplicationMessage
Note: Available only in MongoDB Enterprise15 .
The logApplicationMessage (page 400) command allows users to post a custom message to the
audit log. If running with authorization, users must have clusterAdmin role, or roles that inherit from
clusterAdmin, to run the command.
The logApplicationMessage (page 400) has the following syntax:
{ logApplicationMessage: <string> }
MongoDB associates these custom messages with the audit operation applicationMessage, and the messages are subject to any filtering.
2.3 Operators
Query and Projection Operators (page 400) Query operators provide ways to locate data within the database and
projection operators modify how data is presented.
Update Operators (page 451) Update operators are operators that enable you to modify the data in your database or
add additional data.
Aggregation Pipeline Operators (page 482) Aggregation pipeline operations have a collection of operators available
to define and manipulate documents in pipeline stages.
Query Modifiers (page 555) Query modifiers determine the way that queries will be executed.
2.3.1 Query and Projection Operators
Query Selectors
Comparison
15 http://www.mongodb.com/products/mongodb-enterprise
400
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Comparison Query Operators For comparison of different BSON type values, see the specified BSON comparison
order.
Name
$gt (page 401)
$gte (page 401)
$in (page 402)
$lt (page 403)
$lte (page 403)
$ne (page 404)
$nin (page 404)
Description
Matches values that are greater than the value specified in the query.
Matches values that are greater than or equal to the value specified in the query.
Matches any of the values that exist in an array specified in the query.
Matches values that are less than the value specified in the query.
Matches values that are less than or equal to the value specified in the query.
Matches all values that are not equal to the value specified in the query.
Matches values that do not exist in an array specified to the query.
$gt
$gt
Syntax: {field:
{$gt:
value} }
$gt (page 401) selects those documents where the value of the field is greater than (i.e. >) the specified
value.
For comparison of different BSON type values, see the specified BSON comparison order.
Consider the following example:
db.inventory.find( { qty: { $gt: 20 } } )
This query will select all documents in the inventory collection where the qty field value is greater than
20.
Consider the following example that uses the $gt (page 401) operator with a field from an embedded document:
db.inventory.update( { "carrier.fee": { $gt: 2 } }, { $set: { price: 9.99 } } )
This update() (page 72) operation will set the value of the price field in the first document found containing
the embedded document carrier whose fee field value is greater than 2.
To set the value of the price field in all documents containing the embedded document carrier whose fee
field value is greater than 2, specify the multi:true option in the update() (page 72) method:
db.inventory.update( { "carrier.fee": { $gt: 2 } },
{ $set: { price: 9.99 },
{ multi: true }
)
See also:
find() (page 36), update() (page 72), $set (page 459).
$gte
$gte
Syntax: {field:
{$gte:
value} }
$gte (page 401) selects the documents where the value of the field is greater than or equal to (i.e. >=) a
specified value (e.g. value.)
For comparison of different BSON type values, see the specified BSON comparison order.
Consider the following example:
db.inventory.find( { qty: { $gte: 20 } } )
2.3. Operators
401
MongoDB Reference Manual, Release 2.8.0-rc3
This query would select all documents in inventory where the qty field value is greater than or equal to 20.
Consider the following example which uses the $gte (page 401) operator with a field from an embedded
document:
db.inventory.update( { "carrier.fee": { $gte: 2 } }, { $set: { price: 9.99 } } )
This update() (page 72) operation will set the value of the price field that contain the embedded document
carrier whose fee field value is greater than or equal to 2.
See also:
find() (page 36), update() (page 72), $set (page 459).
$in
$in
The $in (page 402) operator selects the documents where the value of a field equals any value in the specified
array. To specify an $in (page 402) expression, use the following prototype:
For comparison of different BSON type values, see the specified BSON comparison order.
{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }
If the field holds an array, then the $in (page 402) operator selects the documents whose field holds an
array that contains at least one element that matches a value in the specified array (e.g. <value1>, <value2>,
etc.)
Changed in version 2.6: MongoDB 2.6 removes the combinatorial limit for the $in (page 402) operator that
exists for earlier versions16 of the operator.
Examples
Use the $in Operator to Match Values Consider the following example:
db.inventory.find( { qty: { $in: [ 5, 15 ] } } )
This query selects all documents in the inventory collection where the qty field value is either 5 or 15. Although
you can express this query using the $or (page 408) operator, choose the $in (page 402) operator rather than the
$or (page 408) operator when performing equality checks on the same field.
Use the $in Operator to Match Values in an Array The collection inventory contains documents that include
the field tags, as in the following:
{ _id: 1, item: "abc", qty: 10, tags: [ "school", "clothing" ], sale: false }
Then, the following update() (page 72) operation will set the sale field value to true where the tags field holds
an array with at least one element matching either "appliances" or "school".
db.inventory.update(
{ tags: { $in: ["appliances", "school"] } },
{ $set: { sale:true } }
)
16 http://docs.mongodb.org/v2.4/reference/operator/query/in
402
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Use the $in Operator with a Regular Expression The $in (page 402) operator can specify matching values using
regular expressions of the form http://docs.mongodb.org/manual/pattern/. You cannot use $regex
(page 414) operator expressions inside an $in (page 402).
Consider the following example:
db.inventory.find( { tags: { $in: [ /^be/, /^st/ ] } } )
This query selects all documents in the inventory collection where the tags field holds an array that contains at
least one element that starts with either be or st.
See also:
find() (page 36), update() (page 72), $or (page 408), $set (page 459).
$lt
$lt
Syntax: {field:
{$lt:
value} }
$lt (page 403) selects the documents where the value of the field is less than (i.e. <) the specified value.
For comparison of different BSON type values, see the specified BSON comparison order.
Consider the following example:
db.inventory.find( { qty: { $lt: 20 } } )
This query will select all documents in the inventory collection where the qty field value is less than 20.
Consider the following example which uses the $lt (page 403) operator with a field from an embedded document:
db.inventory.update( { "carrier.fee": { $lt: 20 } }, { $set: { price: 9.99 } } )
This update() (page 72) operation will set the price field value in the documents that contain the embedded
document carrier whose fee field value is less than 20.
See also:
find() (page 36), update() (page 72), $set (page 459).
$lte
$lte
Syntax: { field:
{ $lte:
value} }
$lte (page 403) selects the documents where the value of the field is less than or equal to (i.e. <=) the
specified value.
For comparison of different BSON type values, see the specified BSON comparison order.
Consider the following example:
db.inventory.find( { qty: { $lte: 20 } } )
This query will select all documents in the inventory collection where the qty field value is less than or
equal to 20.
Consider the following example which uses the $lt (page 403) operator with a field from an embedded document:
db.inventory.update( { "carrier.fee": { $lte: 5 } }, { $set: { price: 9.99 } } )
2.3. Operators
403
MongoDB Reference Manual, Release 2.8.0-rc3
This update() (page 72) operation will set the price field value in the documents that contain the embedded
document carrier whose fee field value is less than or equal to 5.
See also:
find() (page 36), update() (page 72), $set (page 459).
$ne
$ne
Syntax: {field:
{$ne:
value} }
$ne (page 404) selects the documents where the value of the field is not equal (i.e. !=) to the specified
value. This includes documents that do not contain the field.
For comparison of different BSON type values, see the specified BSON comparison order.
Consider the following example:
db.inventory.find( { qty: { $ne: 20 } } )
This query will select all documents in the inventory collection where the qty field value does not equal
20, including those documents that do not contain the qty field.
Consider the following example which uses the $ne (page 404) operator with a field in an embedded document:
db.inventory.update( { "carrier.state": { $ne: "NY" } }, { $set: { qty: 20 } } )
This update() (page 72) operation will set the qty field value in the documents that contain the embedded
document carrier whose state field value does not equal “NY”, or where the state field or the carrier
embedded document do not exist.
See also:
find() (page 36), update() (page 72), $set (page 459).
$nin
$nin
Syntax: { field:
{ $nin:
[ <value1>, <value2> ...
<valueN> ]} }
$nin (page 404) selects the documents where:
•the field value is not in the specified array or
•the field does not exist.
For comparison of different BSON type values, see the specified BSON comparison order.
Consider the following query:
db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )
This query will select all documents in the inventory collection where the qty field value does not equal 5
nor 15. The selected documents will include those documents that do not contain the qty field.
If the field holds an array, then the $nin (page 404) operator selects the documents whose field holds an
array with no element equal to a value in the specified array (e.g. <value1>, <value2>, etc.).
Consider the following query:
db.inventory.update( { tags: { $nin: [ "appliances", "school" ] } }, { $set: { sale: false } } )
404
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
This update() (page 72) operation will set the sale field value in the inventory collection where
the tags field holds an array with no elements matching an element in the array ["appliances",
"school"] or where a document does not contain the tags field.
See also:
find() (page 36), update() (page 72), $set (page 459).
Logical
Logical Query Operators
Name
$and
(page 405)
$nor
(page 406)
$not
(page 407)
$or (page 408)
Description
Joins query clauses with a logical AND returns all documents that match the condition
clauses.
Joins query clauses with a logical NOR returns all documents that fail to match both cl
Inverts the effect of a query expression and returns documents that do not match the q
expression.
Joins query clauses with a logical OR returns all documents that match the conditions
clause.
$and
$and
New in version 2.0.
Syntax:
{ $and:
<expressionN> } ] }
[ { <expression1> }, { <expression2> } , ...
, {
$and (page 405) performs a logical AND operation on an array of two or more expressions (e.g.
<expression1>, <expression2>, etc.) and selects the documents that satisfy all the expressions
in the array. The $and (page 405) operator uses short-circuit evaluation. If the first expression (e.g.
<expression1>) evaluates to false, MongoDB will not evaluate the remaining expressions.
Note: MongoDB provides an implicit AND operation when specifying a comma separated list of expressions.
Using an explicit AND with the $and (page 405) operator is necessary when the same field or operator has to
be specified in multiple expressions.
Examples
AND Queries With Multiple Expressions Specifying the Same Field Consider the following example:
db.inventory.find( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } )
This query will select all documents in the inventory collection where:
• the price field value is not equal to 1.99 and
• the price field exists.
This query can be also be constructed with an implicit AND operation by combining the operator expressions for the
price field. For example, this query can be written as:
db.inventory.find( { price: { $ne: 1.99, $exists: true } } )
2.3. Operators
405
MongoDB Reference Manual, Release 2.8.0-rc3
AND Queries With Multiple Expressions Specifying the Same Operator Consider the following example:
db.inventory.find( {
$and : [
{ $or : [ { price : 0.99 }, { price : 1.99 } ] },
{ $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
]
} )
This query will return all select all documents where:
• the price field value equals 0.99 or 1.99, and
• the sale field value is equal to true or the qty field value is less than 20.
This query cannot be constructed using an implicit AND operation, because it uses the $or (page 408) operator more
than once.
See also:
find() (page 36), update() (page 72), $ne (page 404), $exists (page 409), $set (page 459).
$nor
$nor
$nor (page 406) performs a logical NOR operation on an array of one or more query expression and selects the
documents that fail all the query expressions in the array. The $nor (page 406) has the following syntax:
{ $nor: [ { <expression1> }, { <expression2> }, ...
{ <expressionN> } ] }
See also:
find() (page 36), update() (page 72), $or (page 408), $set (page 459), and $exists (page 409).
Examples
$nor Query with Two Expressions Consider the following query which uses only the $nor (page 406) operator:
db.inventory.find( { $nor: [ { price: 1.99 }, { sale: true } ]
} )
This query will return all documents that:
• contain the price field whose value is not equal to 1.99 and contain the sale field whose value is not equal
to true or
• contain the price field whose value is not equal to 1.99 but do not contain the sale field or
• do not contain the price field but contain the sale field whose value is not equal to true or
• do not contain the price field and do not contain the sale field
$nor and Additional Comparisons Consider the following query:
db.inventory.find( { $nor: [ { price: 1.99 }, { qty: { $lt: 20 } }, { sale: true } ] } )
This query will select all documents in the inventory collection where:
• the price field value does not equal 1.99 and
• the qty field value is not less than 20 and
• the sale field value is not equal to true
406
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
including those documents that do not contain these field(s).
The exception in returning documents that do not contain the field in the $nor (page 406) expression is when the
$nor (page 406) operator is used with the $exists (page 409) operator.
$nor and $exists Compare that with the following query which uses the $nor (page 406) operator with the
$exists (page 409) operator:
db.inventory.find( { $nor: [ { price: 1.99 }, { price: { $exists: false } },
{ sale: true }, { sale: { $exists: false } } ] } )
This query will return all documents that:
• contain the price field whose value is not equal to 1.99 and contain the sale field whose value is not equal
to true
$not
$not
Syntax: { field:
{ $not:
{ <operator-expression> } } }
$not (page 407) performs a logical NOT operation on the specified <operator-expression> and selects
the documents that do not match the <operator-expression>. This includes documents that do not
contain the field.
Consider the following query:
db.inventory.find( { price: { $not: { $gt: 1.99 } } } )
This query will select all documents in the inventory collection where:
•the price field value is less than or equal to 1.99 or
•the price field does not exist
{ $not: { $gt: 1.99 } } is different from the $lte (page 403) operator. { $lte:
returns only the documents where price field exists and its value is less than or equal to 1.99.
1.99 }
Remember that the $not (page 407) operator only affects other operators and cannot check fields and documents independently. So, use the $not (page 407) operator for logical disjunctions and the $ne (page 404)
operator to test the contents of fields directly.
Consider the following behaviors when using the $not (page 407) operator:
•The operation of the $not (page 407) operator is consistent with the behavior of other operators but may
yield unexpected results with some data types like arrays.
•The $not (page 407) operator does not support operations with the $regex (page 414) operator. Instead use http://docs.mongodb.org/manual// or in your driver interfaces, use your language’s
regular expression capability to create regular expression objects.
Consider
the
following
example
which
http://docs.mongodb.org/manual//:
uses
the
pattern
match
expression
db.inventory.find( { item: { $not: /^p.*/ } } )
The query will select all documents in the inventory collection where the item field value does not
start with the letter p.
If you are using Python, you can write the above query with the PyMongo driver and Python’s
python:re.compile() method to compile a regular expression, as follows:
2.3. Operators
407
MongoDB Reference Manual, Release 2.8.0-rc3
import re
for noMatch in db.inventory.find( { "item": { "$not": re.compile("^p.*") } } ):
print noMatch
See also:
find() (page 36), update() (page 72), $set (page 459), $gt (page 401), $regex (page 414), PyMongo17 , driver.
$or
$or
The $or (page 408) operator performs a logical OR operation on an array of two or more <expressions>
and selects the documents that satisfy at least one of the <expressions>. The $or (page 408) has the
following syntax:
{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }
Consider the following example:
db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )
This query will select all documents in the inventory collection where either the quantity field value is
less than 20 or the price field value equals 10.
Behaviors
$or Clauses and Indexes When evaluating the clauses in the $or (page 408) expression, MongoDB either performs
a collection scan or, if all the clauses are supported by indexes, MongoDB performs index scans. That is, for MongoDB
to use indexes to evaluate an $or (page 408) expression, all the clauses in the $or (page 408) expression must be
supported by indexes. Otherwise, MongoDB will perform a collection scan.
When using indexes with $or (page 408) queries, each clause of an $or (page 408) can use its own index. Consider
the following query:
db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )
To support this query, rather than a compound index, you would create one index on quantity and another index on
price:
db.inventory.ensureIndex( { quantity: 1 } )
db.inventory.ensureIndex( { price: 1 } )
MongoDB can use all but the geoHaystack index to support $or (page 408) clauses.
$or and text Queries Changed in version 2.6.
If $or (page 408) includes a $text (page 417) query, all clauses in the $or (page 408) array must be supported by
an index. This is because a $text (page 417) query must use an index, and $or (page 408) can only use indexes if
all its clauses are supported by indexes. If the $text (page 417) query cannot use an index, the query will return an
error.
17 http://api.mongodb.org/pythoncurrent
408
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
$or and GeoSpatial Queries Changed in version 2.6.
$or supports geospatial clauses (page 423) with the following exception for the near clause (near clause includes
$nearSphere (page 428) and $near (page 429)). $or cannot contain a near clause with any other clause.
$or and Sort Operations Changed in version 2.6.
When executing $or (page 408) queries with a sort() (page 95), MongoDB can now use indexes that support the
$or (page 408) clauses. Previous versions did not use the indexes.
$or versus $in When using $or (page 408) with <expressions> that are equality checks for the value of the
same field, use the $in (page 402) operator instead of the $or (page 408) operator.
For example, to select all documents in the inventory collection where the quantity field value equals either 20
or 50, use the $in (page 402) operator:
db.inventory.find ( { quantity: { $in: [20, 50] } } )
Nested $or Clauses You may nest $or (page 408) operations.
See also:
$and (page 405), find() (page 36), sort() (page 95), $in (page 402)
Element
Element Query Operators
Name
$exists (page 409)
$type (page 411)
Description
Matches documents that have the specified field.
Selects documents if a field is of the specified type.
$exists
Definition
$exists
Syntax: { field:
{ $exists:
<boolean> } }
When <boolean> is true, $exists (page 409) matches the documents that contain the field, including
documents where the field value is null. If <boolean> is false, the query returns only the documents that do
not contain the field.
MongoDB $exists does not correspond to SQL operator exists. For SQL exists, refer to the $in
(page 402) operator.
See also:
$nin (page 404), $in (page 402), and faq-developers-query-for-nulls.
Examples
2.3. Operators
409
MongoDB Reference Manual, Release 2.8.0-rc3
Exists and Not Equal To Consider the following example:
db.inventory.find( { qty: { $exists: true, $nin: [ 5, 15 ] } } )
This query will select all documents in the inventory collection where the qty field exists and its value does not
equal 5 or 15.
Null Values Given a collection named records with the following documents:
{
{
{
{
{
{
{
{
{
{
a:
a:
a:
a:
a:
a:
a:
b:
b:
c:
5, b:
3, b:
null,
1, b:
2, c:
3, b:
4 }
2, c:
2 }
6 }
5, c:
null,
b: 3,
2, c:
5 }
2 }
null }
c: 8 }
c: 9 }
3 }
4 }
Consider the output of the following queries:
Query:
db.records.find( { a: { $exists: true } } )
Result:
{
{
{
{
{
{
{
a:
a:
a:
a:
a:
a:
a:
5, b:
3, b:
null,
1, b:
2, c:
3, b:
4 }
5, c:
null,
b: 3,
2, c:
5 }
2 }
null }
c: 8 }
c: 9 }
3 }
Query:
db.records.find( { b: { $exists: false } } )
Result:
{ a: 2, c: 5 }
{ a: 4 }
{ c: 6 }
Query:
db.records.find( { c: { $exists: false } } )
Result:
{ a: 3, b: 2 }
{ a: 4 }
{ b: 2 }
$type
410
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Definition
$type
Syntax: { field:
{ $type:
<BSON type> } }
$type (page 411) selects the documents where the value of the field is the specified numeric BSON type.
This is useful when dealing with highly unstructured data where data types are not predictable.
Warning: Data models that associate a field name with different data types within a collection are strongly
discouraged.
Without internal consistency complicates application code, and can lead to unnecessary complexity for application developers.
Behavior
Available Types Refer to the following table for the available BSON types and their corresponding numbers.
Type
Double
String
Object
Array
Binary data
Undefined
Object id
Boolean
Date
Null
Regular Expression
JavaScript
Symbol
JavaScript (with scope)
32-bit integer
Timestamp
64-bit integer
Min key
Max key
Number
1
2
3
4
5
6
7
8
9
10
11
13
14
15
16
17
18
255
127
Notes
Deprecated.
Query with -1.
Minimum and Maximum Values MinKey and MaxKey compare less than and greater than all other possible
BSON element values, respectively, and exist primarily for internal use.
To query if a field value is a MinKey, you must use $type (page 411) with -1 as in the following example:
db.collection.find( { field: { $type: -1 } } );
Arrays When applied to arrays, $type (page 411) matches any inner element that is of the specified type. Without
projection this means that the entire array will match if any element has the right type. With projection, the results
will include just those elements of the requested type.
Examples
2.3. Operators
411
MongoDB Reference Manual, Release 2.8.0-rc3
Querying by Data Type Consider the following query:
db.inventory.find( { tags: { $type : 2 } } );
This will list all documents containing a tags field that is either a string or an array holding at least one string. If you
only want to list documents where tags is an array, you could use $where (page 421):
db.inventory.find( { $where : "Array.isArray(this.tags)" } );
Queries that use $where (page 421) requires a complete collection scan and uses Server-side JavaScript.
MinKey and MaxKey The following operation sequence demonstrates both type comparison and the special
MinKey and MaxKey values:
> db.test.insert( [
{
{
{
{
{
>
{
{
{
{
{
{
{
x
x
x
x
x
x
:
:
:
:
:
: 3 },
2.9 },
new Date() },
true },
MaxKey },
MinKey } ] );
db.test.find().sort( { x : 1 } );
"_id" : ObjectId("4b04094b7c65b846e2090112"),
"_id" : ObjectId("4b03155dce8de6586fb002c7"),
"_id" : ObjectId("4b03154cce8de6586fb002c6"),
"_id" : ObjectId("4b031566ce8de6586fb002c9"),
"_id" : ObjectId("4b031563ce8de6586fb002c8"),
"_id" : ObjectId("4b0409487c65b846e2090111"),
"x"
"x"
"x"
"x"
"x"
"x"
:
:
:
:
:
:
{ $minKey : 1 } }
2.9 }
3 }
true }
"Tue Jul 25 2012 18:42:03 GMT-0500 (EST)" }
{ $maxKey : 1 } }
Minimum Shard Key To query for the minimum value of a shard key of a sharded cluster, use the following
operation when connected to the mongos (page 601):
use config
db.chunks.find( { "min.shardKey": { $type: -1 } } )
Additional Information find() (page 36), insert() (page 55), $where (page 421), BSON, shard key, sharded
cluster .
Evaluation
Name
$mod (page 412)
Evaluation Query Operators
$regex
(page 414)
$text (page 417)
$where
(page 421)
Description
Performs a modulo operation on the value of a field and selects documents with
result.
Selects documents where values match a specified regular expression.
Performs text search.
Matches documents that satisfy a JavaScript expression.
$mod
$mod
Select documents where the value of a field divided by a divisor has the specified remainder (i.e. perform a
modulo operation to select documents). To specify a $mod (page 412) expression, use the following syntax:
412
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
{ field: { $mod: [ divisor, remainder ] } }
Changed in version 2.6: The $mod (page 412) operator errors when passed an array with fewer or more elements. In previous versions, if passed an array with one element, the $mod (page 412) operator uses 0 as the
remainder value, and if passed an array with more than two elements, the $mod (page 412) ignores all but the
first two elements. Previous versions do return an error when passed an empty array. See Not Enough Elements
Error (page 413) and Too Many Elements Error (page 414) for details.
Examples
Use $mod to Select Documents Consider a collection inventory with the following documents:
{ "_id" : 1, "item" : "abc123", "qty" : 0 }
{ "_id" : 2, "item" : "xyz123", "qty" : 5 }
{ "_id" : 3, "item" : "ijk123", "qty" : 12 }
Then, the following query selects those documents in the inventory collection where value of the qty field modulo
4 equals 0:
db.inventory.find( { qty: { $mod: [ 4, 0 ] } } )
The query returns the following documents:
{ "_id" : 1, "item" : "abc123", "qty" : 0 }
{ "_id" : 3, "item" : "ijk123", "qty" : 12 }
Not Enough Elements Error
elements.
The $mod (page 412) operator errors when passed an array with fewer than two
Array with Single Element The following operation incorrectly passes the $mod (page 412) operator an array that
contains a single element:
db.inventory.find( { qty: { $mod: [ 4 ] } } )
The statement results in the following error:
error: {
"$err" : "bad query: BadValue malformed mod, not enough elements",
"code" : 16810
}
Changed in version 2.6: In previous versions, if passed an array with one element, the $mod (page 412) operator uses
the specified element as the divisor and 0 as the remainder value.
Empty Array The following operation incorrectly passes the $mod (page 412) operator an empty array:
db.inventory.find( { qty: { $mod: [ ] } } )
The statement results in the following error:
error: {
"$err" : "bad query: BadValue malformed mod, not enough elements",
"code" : 16810
}
2.3. Operators
413
MongoDB Reference Manual, Release 2.8.0-rc3
Changed in version 2.6: Previous versions returned the following error:
error: { "$err" : "mod can't be 0", "code" : 10073 }
Too Many Elements Error The $mod (page 412) operator errors when passed an array with more than two elements.
For example, the following operation attempts to use the $mod (page 412) operator with an array that contains four
elements:
error: {
"$err" : "bad query: BadValue malformed mod, too many elements",
"code" : 16810
}
Changed in version 2.6: In previous versions, if passed an array with more than two elements, the $mod (page 412)
ignores all but the first two elements.
$regex
Definition
$regex
Provides regular expression capabilities for pattern matching strings in queries. MongoDB uses Perl compatible
regular expressions (i.e. “PCRE” ) version 8.30 with UTF-8 support.
To use $regex (page 414), use one of the following syntax:
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
In MongoDB, you can also use regular expression objects (i.e. http://docs.mongodb.org/manual/pattern/)
to specify regular expressions:
{ <field>: /pattern/<options> }
For restrictions on particular syntax use, see $regex vs. /pattern/ Syntax (page 415).
$options
The following <options> are available for use with regular expression.
414
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Option
i
m
x
s
Description
Case insensitivity to match upper and lower cases. For an example, see
Perform Case-Insensitive Regular Expression Match (page 416).
For patterns that include anchors (i.e. ^ for the start, $ for the end), match at
the beginning or end of each line for strings with multiline values. Without
this option, these anchors match at beginning or end of the string. For an
example, see Multiline Match for Lines Starting with Specified Pattern
(page 416).
If the pattern contains no anchors or if the string value has no newline
characters (e.g. \n), the m option has no effect.
“Extended” capability to ignore all white space characters in the $regex
(page 414) pattern unless escaped or included in a character class.
Additionally, it ignores characters in-between and including an un-escaped
hash/pound (#) character and the next new line, so that you may include
comments in complicated patterns. This only applies to data characters; white
space characters may never appear within special character sequences in a
pattern.
The x option does not affect the handling of the VT character (i.e. code 11).
Allows the dot character (i.e. .) to match all characters including newline
characters. For an example, see Use the . Dot Character to Match New Line
(page 417).
Syntax
Restrictions
Requires $regex
with $options
syntax
Requires $regex
with $options
syntax
Behavior
$regex vs. /pattern/ Syntax
$in Expressions To include a regular expression in an $in query expression, you can only use JavaScript regular
expression objects (i.e. http://docs.mongodb.org/manual/pattern/ ). For example:
{ name: { $in: [ /^acme/i, /^ack/ ] } }
You cannot use $regex (page 414) operator expressions inside an $in (page 402).
Implicit AND Conditions for the Field To include a regular expression in a comma-separated list of query conditions
for the field, use the $regex (page 414) operator. For example:
{ name: { $regex: /acme.*corp/i, $nin: [ 'acmeblahcorp' ] } }
{ name: { $regex: /acme.*corp/, $options: 'i', $nin: [ 'acmeblahcorp' ] } }
{ name: { $regex: 'acme.*corp', $options: 'i', $nin: [ 'acmeblahcorp' ] } }
x and s Options To use either the x option or s options, you must use the $regex (page 414) operator expression
with the $options (page 414) operator. For example, to specify the i and the s options, you must use $options
(page 414) for both:
{ name: { $regex: /acme.*corp/, $options: "si" } }
{ name: { $regex: 'acme.*corp', $options: "si" } }
PCRE vs JavaScript To use PCRE supported features in the regex pattern that are unsupported in JavaScript, you
must use the $regex (page 414) operator expression with the pattern as a string. For example, to use (?i) in the
2.3. Operators
415
MongoDB Reference Manual, Release 2.8.0-rc3
pattern to turn case-insensitivity on for the remaining pattern and (?-i) to turn case-sensitivity on for the remaining
pattern, you must use the $regex (page 414) operator with the pattern as a string:
{ name: { $regex: '(?i)a(?-i)cme' } }
Index Use If an index exists for the field, then MongoDB matches the regular expression against the values in the
index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix
expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a
“range” from that prefix and only match against those values from the index that fall within that range.
A regular expression is a “prefix expression” if it starts with a caret (^) or a left anchor (\A), followed by a string of
simple symbols. For example, the regex http://docs.mongodb.org/manual/^abc.*/ will be optimized
by matching only against the values from the index that start with abc.
Additionally, while http://docs.mongodb.org/manual/^a/, http://docs.mongodb.org/manual/^a.*/,
and http://docs.mongodb.org/manual/^a.*$/ match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however,
http://docs.mongodb.org/manual/^a.*/, and http://docs.mongodb.org/manual/^a.*$/
are slower. http://docs.mongodb.org/manual/^a/ can stop scanning after matching the prefix.
Examples The following examples use a collection products with the following documents:
{
{
{
{
"_id"
"_id"
"_id"
"_id"
:
:
:
:
100,
101,
102,
103,
"sku"
"sku"
"sku"
"sku"
:
:
:
:
"abc123",
"abc789",
"xyz456",
"xyz789",
"description"
"description"
"description"
"description"
:
:
:
:
"Single line description." }
"First line\nSecond line" }
"Many spaces before
line" }
"Multiple\nline description" }
Perform Case-Insensitive Regular Expression Match The following example uses the i option perform a caseinsensitive match for documents with sku value that starts with ABC.
db.products.find( { sku: { $regex: /^ABC/i } } )
The query matches the following documents:
{ "_id" : 100, "sku" : "abc123", "description" : "Single line description." }
{ "_id" : 101, "sku" : "abc789", "description" : "First line\nSecond line" }
Multiline Match for Lines Starting with Specified Pattern
lines starting with the letter S for multiline strings:
The following example uses the m option to match
db.products.find( { description: { $regex: /^S/, $options: 'm' } } )
The query matches the following documents:
{ "_id" : 100, "sku" : "abc123", "description" : "Single line description." }
{ "_id" : 101, "sku" : "abc789", "description" : "First line\nSecond line" }
Without the m option, the query would match just the following document:
{ "_id" : 100, "sku" : "abc123", "description" : "Single line description." }
If the $regex (page 414) pattern does not contain an anchor, the pattern matches against the string as a whole, as in
the following example:
416
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.products.find( { description: { $regex: /S/ } } )
Then, the $regex (page 414) would match both documents:
{ "_id" : 100, "sku" : "abc123", "description" : "Single line description." }
{ "_id" : 101, "sku" : "abc789", "description" : "First line\nSecond line" }
Use the . Dot Character to Match New Line The following example uses the s option to allow the dot character
(i.e. .) to match all characters including new line as well as the i option to perform a case-insensitive match:
db.products.find( { description: { $regex: /m.*line/, $options: 'si' } } )
The query matches the following documents:
{ "_id" : 102, "sku" : "xyz456", "description" : "Many spaces before
line" }
{ "_id" : 103, "sku" : "xyz789", "description" : "Multiple\nline description" }
Without the s option, the query would have matched only the following document:
{ "_id" : 102, "sku" : "xyz456", "description" : "Many spaces before
line" }
Ignore White Spaces in Pattern The following example uses the x option ignore white spaces and the comments,
denoted by the # and ending with the \n in the matching pattern:
var pattern = "abc #category code\n123 #item number"
db.products.find( { sku: { $regex: pattern, $options: "x" } } )
The query matches the following document:
{ "_id" : 100, "sku" : "abc123", "description" : "Single line description." }
$text
$text
New in version 2.6.
$text (page 417) performs a text search on the content of the fields indexed with a text index. A $text
(page 417) expression has the following syntax:
{ $text: { $search: <string>, $language: <string> } }
The $text (page 417) operator accepts a text query document with the following fields:
field string $search A string of terms that MongoDB parses and uses to query the text index. MongoDB performs a logical OR search of the terms unless specified as a phrase. See Behavior
(page 417) for more information on the field.
field string $language The language that determines the list of stop words for the search and the
rules for the stemmer and tokenizer. If not specified, the search uses the default language of the
index. For supported languages, see text-search-languages.
If you specify a language value of "none", then the text search uses simple tokenization with
no list of stop words and no stemming.
The $text (page 417) operator, by default, does not return results sorted in terms of the results’ score. For
more information, see the Text Score (page 419) documentation.
Behavior
2.3. Operators
417
MongoDB Reference Manual, Release 2.8.0-rc3
Restrictions
• A query can specify, at most, one $text (page 417) expression.
• The $text (page 417) query can not appear in $nor (page 406) expressions.
• To use a $text (page 417) query in an $or (page 408) expression, all clauses in the $or (page 408) array
must be indexed.
• You cannot use hint() (page 87) if the query includes a $text (page 417) query expression.
• You cannot specify $natural (page 563) sort order if the query includes a $text (page 417) expression.
• You cannot combine the $text (page 417) expression, which requires a special text index, with a query operator
that requires a different type of special index. For example you cannot combine $text (page 417) expression
with the $near (page 429) operator.
$search Field In the $search field, specify a string of words that the text operator parses and uses to query
the text index. The text operator treats most punctuation in the string as delimiters, except a hyphen - that
negates term or an escaped double quotes \" that specifies a phrase.
Phrases To match on a phrase, as opposed to individual terms, enclose the phrase in escaped double quotes (\"), as
in:
"\"ssl certificate\""
If the $search string includes a phrase and individual terms, text search will only match the documents that include
the phrase. More specifically, the search performs a logical AND of the phrase with the individual terms in the search
string.
For example, passed a $search string:
"\"ssl certificate\" authority key"
The $text (page 417) operator searches for the phrase "ssl certificate" and ("authority" or "key"
or "ssl" or "certificate" ).
Negations Prefixing a word with a hyphen sign (-) negates a word:
• The negated word excludes documents that contain the negated word from the result set.
• When passed a search string that only contains negated words, text search will not match any documents.
• A hyphenated word, such as pre-market, is not a negation. The $text (page 417) operator treats the hyphen
as a delimiter.
The $text (page 417) operator adds all negations to the query with the logical AND operator.
Match Operation The $text (page 417) operator ignores language-specific stop words, such as the and and in
English.
The $text (page 417) operator matches on the complete stemmed word. So if a document field contains the word
blueberry, a search on the term blue will not match. However, blueberry or blueberries will match.
For non-diacritics, text search is case insensitive; i.e. case insensitive for [A-z].
418
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Text Score The $text (page 417) operator assigns a score to each document that contains the search term in
the indexed fields. The score represents the relevance of a document to a given text search query. The score can
be part of a sort() (page 95) method specification as well as part of the projection expression. The { $meta:
"textScore" } expression provides information on the processing of the $text (page 417) operation. See
$meta (page 449) projection operator for details on accessing the score for projection or sort.
Examples The following examples assume a collection articles that has a text index on the field subject:
db.articles.ensureIndex( { subject: "text" } )
Search for a Single Word The following query searches for the term coffee:
db.articles.find( { $text: { $search: "coffee" } } )
This query returns documents that contain the term coffee in the indexed subject field.
Match Any of the Search Terms If the search string is a space-delimited string, $text (page 417) operator performs a logical OR search on each term and returns documents that contains any of the terms.
The following query searches specifies a $search string of three terms delimited by space, "bake coffee
cake":
db.articles.find( { $text: { $search: "bake coffee cake" } } )
This query returns documents that contain either bake or coffee or cake in the indexed subject field.
Search for a Phrase To match the exact phrase as a single term, escape the quotes.
The following query searches for the phrase coffee cake:
db.articles.find( { $text: { $search: "\"coffee cake\"" } } )
This query returns documents that contain the phrase coffee cake.
See also:
Phrases (page 418)
Exclude Documents That Contain a Term A negated term is a term that is prefixed by a minus sign -. If you
negate a term, the $text (page 417) operator will exclude the documents that contain those terms from the results.
The following example searches for documents that contain the words bake or coffee but do not contain the term
cake:
db.articles.find( { $text: { $search: "bake coffee -cake" } } )
See also:
Negations (page 418)
Return the Text Search Score The following query searches for the term cake and returns the score assigned to
each matching document:
2.3. Operators
419
MongoDB Reference Manual, Release 2.8.0-rc3
db.articles.find(
{ $text: { $search: "cake" } },
{ score: { $meta: "textScore" } }
)
In the result set, the returned documents includes an additional field score that contains the document’s score associated with the text search. 18
See also:
Text Score (page 419)
Sort by Text Search Score To sort by the text score, include the same $meta (page 449) expression in both the
projection document and the sort expression. 1 The following query searches for the term cake and sorts the results
by the descending score:
db.articles.find(
{ $text: { $search: "cake" } },
{ score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )
In the result set, the returned documents includes an additional field score that contains the document’s score associated with the text search.
See also:
Text Score (page 419)
Return Top 3 Matching Documents Use the limit() (page 88) method in conjunction with a sort() (page 95)
to return the top three matching documents. The following query searches for the term cake and sorts the results by
the descending score:
db.articles.find(
{ $text: { $search: "cake" } },
{ score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } ).limit(3)
See also:
Text Score (page 419)
Text Search with Additional Query and Sort Expressions The following query searches for documents with
status equal to "A" that contain the terms coffee or cake in the indexed field subject and specifies a sort order
of ascending date, descending text score:
db.articles.find(
{ status: "A", $text: { $search: "coffee cake" } },
{ score: { $meta: "textScore" } }
).sort( { date: 1, score: { $meta: "textScore" } } )
Search a Different Language Use the optional $language field in the $text (page 417) expression to specify a
language that determines the list of stop words and the rules for the stemmer and tokenizer for the search string.
18 The behavior and requirements of the $meta (page 449) operator differs from that of the $meta (page 529) aggregation operator. See the
$meta (page 529) aggregation operator for details.
420
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
If you specify a language value of "none", then the text search uses simple tokenization with no list of stop words
and no stemming.
The following query specifies es for Spanish as the language that determines the tokenization, stemming, and stop
words:
db.articles.find(
{ $text: { $search: "leche", $language: "es" } }
)
The $text (page 417) expression can also accept the language by name, spanish. See text-search-languages for
the supported languages.
See also:
http://docs.mongodb.org/manual/tutorial/text-search-in-aggregation
$where
$where
Use the $where (page 421) operator to pass either a string containing a JavaScript expression or a full
JavaScript function to the query system. The $where (page 421) provides greater flexibility, but requires
that the database processes the JavaScript expression or function for each document in the collection. Reference
the document in the JavaScript expression or function using either this or obj .
Behavior
Map Reduce Changed in version 2.4.
In MongoDB 2.4, map-reduce operations (page 220), the group (page 216) command, and $where
(page 421) operator expressions cannot access certain global functions or properties, such as db, that are available in
the mongo (page 610) shell.
When upgrading to MongoDB 2.4, you will need to refactor your code if your map-reduce operations
(page 220), group (page 216) commands, or $where (page 421) 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 220), the
group (page 216) command, and $where (page 421) operator expressions in MongoDB 2.4:
2.3. Operators
421
MongoDB Reference Manual, Release 2.8.0-rc3
Available Properties
Available Functions
args
MaxKey
MinKey
assert()
BinData()
DBPointer()
DBRef()
doassert()
emit()
gc()
HexData()
hex_md5()
isNumber()
isObject()
ISODate()
isString()
Map()
MD5()
NumberInt()
NumberLong()
ObjectId()
print()
printjson()
printjsononeline()
sleep()
Timestamp()
tojson()
tojsononeline()
tojsonObject()
UUID()
version()
elemMatch Changed in version 2.6.
Only apply the $where (page 421) query operator to top-level documents. The $where (page 421) query operator
will not work inside a nested document, for instance, in an $elemMatch (page 442) query.
Considerations
• Do not write to the database within the $where (page 421) JavaScript function.
• $where (page 421) evaluates JavaScript and cannot take advantage of indexes. Therefore, query performance
improves when you express your query using the standard MongoDB operators (e.g., $gt (page 401), $in
(page 402)).
• In general, you should use $where (page 421) only when you can’t express your query using another operator.
If you must use $where (page 421), try to include at least one other standard query operator to filter the result
set. Using $where (page 421) alone requires a table scan.
Using normal non-$where (page 421) query statements provides the following performance advantages:
• MongoDB will evaluate non-$where (page 421) components of query before $where (page 421) statements.
If the non-$where (page 421) statements match no documents, MongoDB will not perform any query evaluation using $where (page 421).
• The non-$where (page 421) query statements may use an index.
Examples Consider the following examples:
db.myCollection.find( { $where: "this.credits == this.debits" } );
db.myCollection.find( { $where: "obj.credits == obj.debits" } );
db.myCollection.find( { $where: function() { return (this.credits == this.debits) } } );
db.myCollection.find( { $where: function() { return obj.credits == obj.debits; } } );
Additionally, if the query consists only of the $where (page 421) operator, you can pass in just the JavaScript
expression or JavaScript functions, as in the following examples:
422
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
db.myCollection.find( "this.credits == this.debits || this.credits > this.debits" );
db.myCollection.find( function() { return (this.credits == this.debits || this.credits > this.debits
You can include both the standard MongoDB operators and the $where (page 421) operator in your query, as in the
following examples:
db.myCollection.find( { active: true, $where: "this.credits - this.debits < 0" } );
db.myCollection.find( { active: true, $where: function() { return obj.credits - obj.debits < 0; } } )
Geospatial
Geospatial Query Operators
Operators
Query Selectors
Name
Description
$geoIntersects Selects geometries that intersect with a GeoJSON geometry. The 2dsphere index supports
(page 423)
$geoIntersects (page 423).
$geoWithin
Selects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d indexes
(page 425)
support $geoWithin (page 425).
$nearSphere
Returns geospatial objects in proximity to a point on a sphere. Requires a geospatial index.
(page 428)
The 2dsphere and 2d indexes support $nearSphere (page 428).
$near
Returns geospatial objects in proximity to a point. Requires a geospatial index. The
(page 429)
2dsphere and 2d indexes support $near (page 429).
$geoIntersects
Definition
$geoIntersects
New in version 2.4.
Selects documents whose geospatial data intersects with a specified GeoJSON object; i.e. where the intersection
of the data and the specified object is non-empty. This includes cases where the data and the specified object
share an edge.
The $geoIntersects (page 423) operator uses the $geometry (page 434) operator to specify the GeoJSON object. To specify a GeoJSON polygons or multipolygons using the default coordinate reference system
(CRS), use the following syntax:
{
<location field>: {
$geoIntersects: {
$geometry: {
type: "<GeoJSON object type>" ,
coordinates: [ <coordinates> ]
}
}
}
}
2.3. Operators
423
MongoDB Reference Manual, Release 2.8.0-rc3
For $geoIntersects (page 423) queries that specify GeoJSON geometries with areas greater than a single
hemisphere, the use of the default CRS results in queries for the complementary geometries.
New in version 2.8: To specify a single-ringed GeoJSON polygon with a custom MongoDB CRS, use the
following prototype that specifies the custom MongoDB CRS in the $geometry (page 434) expression:
{
<location field>: {
$geoIntersects: {
$geometry: {
type: "Polygon" ,
coordinates: [ <coordinates> ],
crs: {
type: "name",
properties: { name: "urn:x-mongodb:crs:strictwinding:EPSG:4326" }
}
}
}
}
}
The custom MongoDB CRS uses a counter-clockwise winding order and allows $geoIntersects (page 423)
to support queries with a single-ringed GeoJSON polygon whose area is greater than or equal to a single hemisphere. If the specified polygon is smaller than a single hemisphere, the behavior of $geoIntersects
(page 423) with the MongoDB CRS is the same as with the default CRS. See also “Big” Polygons (page 424).
Important: If you use longitude and latitude, specify coordinates in order of: longitude, latitude.
Behavior
Geospatial Indexes $geoIntersects (page 423) uses spherical geometry. $geoIntersects (page 423) does
not require a geospatial index. However, a geospatial index will improve query performance. Only the 2dsphere
geospatial index supports $geoIntersects (page 423).
“Big” Polygons For $geoIntersects (page 423), if you specify a single-ringed polygon that has an area
greater than a single hemisphere, include the custom MongoDB coordinate reference system in
the $geometry (page 434) expression; otherwise, $geoIntersects (page 423) queries for the complementary
geometry. For all other GeoJSON polygons with areas greater than a hemisphere, $geoIntersects (page 423)
queries for the complementary geometry.
Examples
Intersects a Polygon The following example uses $geoIntersects (page 423) to select all loc data that intersect with the geojson-polygon defined by the coordinates array. The area of the polygon is less than the area of a
single hemisphere:
db.places.find(
{
loc: {
$geoIntersects: {
$geometry: {
type: "Polygon" ,
coordinates: [
424
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
[ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ], [ 0, 0 ] ]
]
}
}
}
}
)
For single-ringed polygons with areas greater than a single hemisphere, see Intersects a “Big” Polygon (page 425).
Intersects a “Big” Polygon To query with a single-ringed GeoJSON polygon whose area is greater than a single
hemisphere, the $geometry (page 434) expression must specify the custom MongoDB coordinate reference system.
For example:
db.places.find(
{
loc: {
$geoIntersects: {
$geometry: {
type : "Polygon",
coordinates: [
[
[ -100, 60 ], [ -100, 0 ], [ -100, -60 ], [ 100, -60 ], [ 100, 60 ], [ -100, 60 ]
]
],
crs: {
type: "name",
properties: { name: "urn:x-mongodb:crs:strictwinding:EPSG:4326" }
}
}
}
}
}
)
$geoWithin
Definition
$geoWithin
New in version 2.4: $geoWithin (page 425) replaces $within (page 427) which is deprecated.
Selects documents with geospatial data that exists entirely within a specified shape. When determining inclusion,
MongoDB considers the border of a shape to be part of the shape, subject to the precision of floating point
numbers.
The specified shape can be either a GeoJSON geojson-polygon (either single-ringed or multi-ringed), a GeoJSON geojson-multipolygon, or a shape defined by legacy coordinate pairs. The $geoWithin (page 425)
operator uses the $geometry (page 434) operator to specify the GeoJSON object.
To specify a GeoJSON polygons or multipolygons using the default coordinate reference system (CRS), use the
following syntax:
{
<location field>: {
$geoWithin: {
$geometry: {
2.3. Operators
425
MongoDB Reference Manual, Release 2.8.0-rc3
type: <"Polygon" or "MultiPolygon"> ,
coordinates: [ <coordinates> ]
}
}
}
}
For $geoWithin (page 425) queries that specify GeoJSON geometries with areas greater than a single hemisphere, the use of the default CRS results in queries for the complementary geometries.
New in version 2.8: To specify a single-ringed GeoJSON polygon with a custom MongoDB CRS, use the
following prototype that specifies the custom MongoDB CRS in the $geometry (page 434) expression:
{
<location field>: {
$geoWithin: {
$geometry: {
type: "Polygon" ,
coordinates: [ <coordinates> ],
crs: {
type: "name",
properties: { name: "urn:x-mongodb:crs:strictwinding:EPSG:4326" }
}
}
}
}
}
The custom MongoDB CRS uses a counter-clockwise winding order and allows $geoWithin (page 425) to
support queries with a single-ringed GeoJSON polygon whose area is greater than or equal to a single hemisphere. If the specified polygon is smaller than a single hemisphere, the behavior of $geoWithin (page 425)
with the MongoDB CRS is the same as with the default CRS. See also “Big” Polygons (page 427).
If querying for inclusion in a shape defined by legacy coordinate pairs on a plane, use the following syntax:
{
<location field>: {
$geoWithin: { <shape operator>: <coordinates> }
}
}
The available shape operators are:
•$box (page 432),
•$polygon (page 436),
•$center (page 433) (defines a circle), and
•$centerSphere (page 432) (defines a circle on a sphere).
Important: If you use longitude and latitude, specify coordinates in order of longitude, latitude.
Behavior
Geospatial Indexes $geoWithin (page 425) does not require a geospatial index. However, a geospatial index will
improve query performance. Both 2dsphere and 2d geospatial indexes support $geoWithin (page 425).
426
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Unsorted Results The $geoWithin (page 425) operator does not return sorted results. As such, MongoDB can return $geoWithin (page 425) queries more quickly than geospatial $near (page 429) or $nearSphere (page 428)
queries, which sort results.
“Big” Polygons For $geoWithin (page 425), if you specify a single-ringed polygon that has an area greater
than a single hemisphere, include the custom MongoDB coordinate reference system in the
$geometry (page 434) expression; otherwise, $geoWithin (page 425) queries for the complementary geometry. For all other GeoJSON polygons with areas greater than a hemisphere, $geoWithin (page 425) queries for the
complementary geometry.
Examples
Within a Polygon The following example selects all loc data that exist entirely within a GeoJSON geojsonpolygon. The area of the polygon is less than the area of a single hemisphere:
db.places.find(
{
loc: {
$geoWithin: {
$geometry: {
type : "Polygon" ,
coordinates: [ [ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ], [ 0, 0 ] ] ]
}
}
}
}
)
For single-ringed polygons with areas greater than a single hemisphere, see Within a “Big” Polygon (page 427).
Within a “Big” Polygon To query with a single-ringed GeoJSON polygon whose area is greater than a single
hemisphere, the $geometry (page 434) expression must specify the custom MongoDB coordinate reference system.
For example:
db.places.find(
{
loc: {
$geoWithin: {
$geometry: {
type : "Polygon" ,
coordinates: [
[
[ -100, 60 ], [ -100, 0 ], [ -100, -60 ], [ 100, -60 ], [ 100, 60 ], [ -100, 60 ]
]
],
crs: {
type: "name",
properties: { name: "urn:x-mongodb:crs:strictwinding:EPSG:4326" }
}
}
}
}
}
)
2.3. Operators
427
MongoDB Reference Manual, Release 2.8.0-rc3
$within
Deprecated since version 2.4: $geoWithin (page 425) replaces $within (page 427) in MongoDB 2.4.
$nearSphere
Definition
$nearSphere
Specifies a point for which a geospatial query returns the documents from nearest to farthest. MongoDB calculates distances for $nearSphere (page 428) using spherical geometry.
$nearSphere (page 428) requires a geospatial index:
•2dsphere index for location data defined as GeoJSON points
•2d index for location data defined as legacy coordinate pairs. To use a 2d index on GeoJSON points,
create the index on the coordinates field of the GeoJSON object.
The $nearSphere (page 428) operator can specify either a GeoJSON point or legacy coordinate point.
To specify a GeoJSON point, use the following syntax:
{
$nearSphere: {
$geometry: {
type : "Point",
coordinates : [ <longitude>, <latitude> ]
},
$minDistance: <distance in meters>,
$maxDistance: <distance in meters>
}
}
•The optional $minDistance (page 435) is available only if the query uses the 2dsphere index.
$minDistance (page 435) limits the results to those documents that are at least the specified distance
from the center point.
New in version 2.6.
•The optional $maxDistance (page 434) is available for either index.
To specify a point using legacy coordinates, use the following syntax:
{
$nearSphere: [ <x>, <y> ],
$minDistance: <distance in radians>,
$maxDistance: <distance in radians>
}
•The optional $minDistance (page 435) is available only if the query uses the 2dsphere index.
$minDistance (page 435) limits the results to those documents that are at least the specified distance
from the center point.
New in version 2.6.
•The optional $maxDistance (page 434) is available for either index.
If you use longitude and latitude for legacy coordinates, specify the longitude first, then latitude.
See also:
428
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
2d Indexes and Geospatial Near Queries (page 716)
Examples
Specify Center Point Using GeoJSON
field and has a 2dsphere index.
Consider a collection places that contains documents with a location
Then, the following example returns whose location is at least 1000 meters from and at most 5000 meters from
the specified point, ordered from nearest to farthest:
db.places.find(
{
location: {
$nearSphere: {
$geometry: {
type : "Point",
coordinates : [ -73.9667, 40.78 ]
},
$minDistance: 1000,
$maxDistance: 5000
}
}
}
)
Specify Center Point Using Legacy Coordinates
2d Index Consider a collection legacyPlaces that contains documents with legacy coordinates pairs in the
location field and has a 2d index.
Then, the following example returns those documents whose location is at most 0.10 radians from the specified
point, ordered from nearest to farthest:
db.legacyPlaces.find(
{ location : { $nearSphere : [ -73.9667, 40.78 ], $maxDistance: 0.10 } }
)
2dsphere Index If the collection has a 2dsphere index instead, you can also specify the optional
$minDistance (page 435) specification. For example, the following example returns the documents whose
location is at least 0.0004 radians from the specified point, ordered from nearest to farthest:
db.legacyPlaces.find(
{ location : { $nearSphere : [ -73.9667, 40.78 ], $minDistance: 0.0004 } }
)
$near
Definition
$near
Specifies a point for which a geospatial query returns the documents from nearest to farthest. The $near
(page 429) operator can specify either a GeoJSON point or legacy coordinate point.
$near (page 429) requires a geospatial index:
2.3. Operators
429
MongoDB Reference Manual, Release 2.8.0-rc3
•2dsphere index if specifying a GeoJSON point,
•2d index if specifying a point using legacy coordinates.
To specify a GeoJSON point, $near (page 429) operator requires a 2dsphere index and has the following
syntax:
{
$near: {
$geometry: {
type: "Point" ,
coordinates: [ <longitude> , <latitude> ]
},
$maxDistance: <distance in meters>,
$minDistance: <distance in meters>
}
}
When specifying a GeoJSON point, you can use the optional $minDistance (page 435) and
$maxDistance (page 434) specifications to limit the $near (page 429) results by distance in meters:
•$minDistance (page 435) limits the results to those documents that are at least the specified distance
from the center point. $minDistance (page 435) is only available for use with 2dsphere index.
New in version 2.6.
•$maxDistance (page 434) limits the results to those documents that are at most the specified distance
from the center point.
To specify a point using legacy coordinates, $near (page 429) requires a 2d index and has the following
syntax:
{
$near: [ <x>, <y> ],
$maxDistance: <distance in radians>
}
If you use longitude and latitude for legacy coordinates, specify the longitude first, then latitude.
When specifying a legacy coordinate, you can use the optional $maxDistance (page 434) specification to
limit the $near (page 429) results by distance in radians. $maxDistance (page 434) limits the results to
those documents that are at most the specified distance from the center point.
Behavior
• You cannot combine the $near (page 429) operator, which requires a special geospatial index, with a query
operator or command that uses a different type of special index. For example you cannot combine $near
(page 429) with the $text (page 417) query.
• For sharded collections, queries using $near (page 429) are not supported. You can instead use either the
geoNear (page 229) command or the $geoNear (page 484) aggregation stage.
• $near (page 429) always returns the documents sorted by distance. Any other sort order requires to sort the
documents in memory, which can be inefficient. To return results in a different sort order, use the $geoWithin
operator and the sort() method.
See also:
2d Indexes and Geospatial Near Queries (page 716)
Examples
430
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Query on GeoJSON Data
Important: Specify coordinates in this order: “longitude, latitude.”
Consider a collection places that has a 2dsphere index.
The following example returns documents that are at least 1000 meters from and at most 5000 meters from the
specified GeoJSON point, sorted from nearest to farthest:
db.places.find(
{
location:
{ $near :
{
$geometry: { type: "Point",
$minDistance: 1000,
$maxDistance: 5000
}
}
}
)
coordinates: [ -73.9667, 40.78 ] },
Query on Legacy Coordinates
Important: Specify coordinates in this order: “longitude, latitude.”
Consider a collection legacy2d that has a 2d index.
The following example returns documents that are at most 0.10 radians from the specified legacy coordinate pair,
sorted from nearest to farthest:
db.legacy2d.find(
{ location : { $near : [ -73.9667, 40.78 ], $maxDistance: 0.10 } }
)
Name
$box
(page 432)
$centerSphere
(page 432)
Geometry Specifiers
$center
(page 433)
$geometry
(page 434)
$maxDistance
(page 434)
$minDistance
(page 435)
$polygon
(page 436)
$uniqueDocs
(page 437)
Description
Specifies a rectangular box using legacy coordinate pairs for $geoWithin (page 425)
queries. The 2d index supports $box (page 432).
Specifies a circle using either legacy coordinate pairs or GeoJSON format for $geoWith
(page 425) queries when using spherical geometry. The 2dsphere and 2d indexes suppo
$centerSphere (page 432).
Specifies a circle using legacy coordinate pairs to $geoWithin (page 425) queries when
using planar geometry. The 2d index supports $center (page 433).
Specifies a geometry in GeoJSON format to geospatial query operators.
Specifies a maximum distance to limit the results of $near (page 429) and $nearSpher
(page 428) queries. The 2dsphere and 2d indexes support $centerSphere (page 43
Specifies a minimum distance to limit the results of $near (page 429) and $nearSpher
(page 428) queries. For use with 2dsphere index only.
Specifies a polygon to using legacy coordinate pairs for $geoWithin (page 425) queries
The 2d index supports $center (page 433).
Deprecated. Modifies a $geoWithin (page 425) and $near (page 429) queries to ensu
that even if a document matches the query multiple times, the query returns the document
once.
$box
2.3. Operators
431
MongoDB Reference Manual, Release 2.8.0-rc3
Definition
$box
Specifies a rectangle for a geospatial $geoWithin (page 425) query to return documents that are within the
bounds of the rectangle, according to their point-based location data. When used with the $box (page 432) operator, $geoWithin (page 425) returns documents based on grid coordinates and does not query for GeoJSON
shapes.
To use the $box (page 432) operator, you must specify the bottom left and top right corners of the rectangle in
an array object:
{
<location field>: {
$geoWithin: {
$box: [
[ <bottom left coordinates> ],
[ <upper right coordinates> ]
]
}
}
}
Important: If you use longitude and latitude, specify longitude first.
Behavior The query calculates distances using flat (planar) geometry.
Changed in version 2.2.3: Applications can use $box (page 432) without having a geospatial index. However, geospatial indexes support much faster queries than the unindexed equivalents. Before 2.2.3, a geospatial index must exist on
a field holding coordinates before using any of the geospatial query operators.
Only the 2d geospatial index supports $box (page 432).
Example The following example query returns all documents that are within the box having points at: [ 0 , 0
], [ 0 , 100 ], [ 100 , 0 ], and [ 100 , 100 ].
db.places.find( {
loc: { $geoWithin: { $box:
} )
[ [ 0, 0 ], [ 100, 100 ] ] } }
$centerSphere
Definition
$centerSphere
New in version 1.8.
Defines a circle for a geospatial query that uses spherical geometry. The query returns documents that are within
the bounds of the circle. You can use the $centerSphere (page 432) operator on both GeoJSON objects and
legacy coordinate pairs.
To use $centerSphere (page 432), specify an array that contains:
•The grid coordinates of the circle’s center point, and
•The
circle’s
radius
measured
in
radians.
To
calculate
radians,
see
http://docs.mongodb.org/manual/tutorial/calculate-distances-using-spherical-geometr
432
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
{
<location field>: {
$geoWithin: { $centerSphere: [ [ <x>, <y> ], <radius> ] }
}
}
Important: If you use longitude and latitude, specify longitude first.
Behavior Changed in version 2.2.3: Applications can use $centerSphere (page 432) without having a geospatial
index. However, geospatial indexes support much faster queries than the unindexed equivalents. Before 2.2.3, a
geospatial index must exist on a field holding coordinates before using any of the geospatial query operators.
Both 2dsphere and 2d geospatial indexes support $centerSphere (page 432).
Example The following example queries grid coordinates and returns all documents within a 10 mile radius of
longitude 88 W and latitude 30 N. The query converts the distance to radians by dividing by the approximate radius
of the earth, 3959 miles:
db.places.find( {
loc: { $geoWithin: { $centerSphere: [ [ -88, 30 ], 10/3959 ] } }
} )
$center
Definition
$center
New in version 1.4.
The $center (page 433) operator specifies a circle for a $geoWithin (page 425) query. The query returns
legacy coordinate pairs that are within the bounds of the circle. The operator does not return GeoJSON objects.
To use the $center (page 433) operator, specify an array that contains:
•The grid coordinates of the circle’s center point, and
•The circle’s radius, as measured in the units used by the coordinate system.
{
<location field>: {
$geoWithin: { $center: [ [ <x>, <y> ] , <radius> ] }
}
}
Important: If you use longitude and latitude, specify longitude first.
Behavior The query calculates distances using flat (planar) geometry.
Changed in version 2.2.3: Applications can use $center (page 433) without having a geospatial index. However,
geospatial indexes support much faster queries than the unindexed equivalents. Before 2.2.3, a geospatial index must
exist on a field holding coordinates before using any of the geospatial query operators.
Only the 2d geospatial index supports $center (page 433).
2.3. Operators
433
MongoDB Reference Manual, Release 2.8.0-rc3
Example The following example query returns all documents that have coordinates that exist within the circle centered on [ -74, 40.74 ] and with a radius of 10:
db.places.find(
{ loc: { $geoWithin: { $center: [ [-74, 40.74], 10 ] } } }
)
$geometry
$geometry
New in version 2.4.
Changed in version 2.8: Add support to specify single-ringed GeoJSON polygons with areas greater than a
single hemisphere.
The $geometry (page 434) operator specifies a GeoJSON geometry for use with the following geospatial query operators: $geoWithin (page 425), $geoIntersects (page 423), $near (page 429), and
$nearSphere (page 428). $geometry (page 434) uses EPSG:4326 as the default coordinate reference
system (CRS).
To specify GeoJSON objects with the default CRS, use the following prototype for $geometry (page 434):
$geometry: {
type: "<GeoJSON object type>",
coordinates: [ <coordinates> ]
}
New in version 2.8: To specify a single-ringed GeoJSON polygon with a custom MongoDB CRS, use the
following prototype (available only for $geoWithin (page 425) and $geoIntersects (page 423)):
$geometry: {
type: "Polygon",
coordinates: [ <coordinates> ],
crs: {
type: "name",
properties: { name: "urn:x-mongodb:crs:strictwinding:EPSG:4326" }
}
}
The custom MongoDB coordinate reference system has a strict counter-clockwise winding order.
Important: If you use longitude and latitude, specify coordinates in order of: longitude, latitude.
$maxDistance
Definition
$maxDistance
The $maxDistance (page 434) operator constrains the results of a geospatial $near (page 429) or
$nearSphere (page 428) query to the specified distance. The measuring units for the maximum distance
are determined by the coordinate system in use. For GeoJSON point object, specify the distance in meters, not
radians.
Changed in version 2.6: Specify a non-negative number for $maxDistance (page 434).
The 2dsphere and 2d geospatial indexes both support $maxDistance (page 434): .
434
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Example The following example query returns documents with location values that are 10 or fewer units from the
point [ 100 , 100 ].
db.places.find( {
loc: { $near: [ 100 , 100 ],
} )
$maxDistance: 10 }
MongoDB orders the results by their distance from [ 100 , 100 ]. The operation returns the first 100 results,
unless you modify the query with the cursor.limit() (page 88) method.
$minDistance
Definition
$minDistance
New in version 2.6.
Filters the results of a geospatial $near (page 429) or $nearSphere (page 428) query to those documents
that are at least the specified distance from the center point.
$minDistance (page 435) is available for use with 2dsphere index only.
If $near (page 429) or $nearSphere (page 428) query specifies the center point as a GeoJSON point, specify
the distance as a non-negative number in meters.
If $nearSphere (page 428) query specifies the center point as legacy coordinate pair, specify the distance as
a non-negative number in radians. $near (page 429) can only use the 2dsphere index if the query specifies
the center point as a GeoJSON point.
Examples
Use with $near
Important: Specify coordinates in this order: “longitude, latitude.”
Consider a collection places that has a 2dsphere index.
The following example returns documents that are at least 1000 meters from and at most 5000 meters from the
specified GeoJSON point, sorted from nearest to farthest:
db.places.find(
{
location:
{ $near :
{
$geometry: { type: "Point",
$minDistance: 1000,
$maxDistance: 5000
}
}
}
)
coordinates: [ -73.9667, 40.78 ] },
Use with $nearSphere Consider a collection places that contains documents with a location field and has
a 2dsphere index.
Then, the following example returns whose location is at least 1000 meters from and at most 5000 meters from
the specified point, ordered from nearest to farthest:
2.3. Operators
435
MongoDB Reference Manual, Release 2.8.0-rc3
db.places.find(
{
location: {
$nearSphere: {
$geometry: {
type : "Point",
coordinates : [ -73.9667, 40.78 ]
},
$minDistance: 1000,
$maxDistance: 5000
}
}
}
)
For an example that specifies the center point as legacy coordinate pair, see $nearSphere (page 428)
$polygon
Definition
$polygon
New in version 1.9.
Specifies a polygon for a geospatial $geoWithin (page 425) query on legacy coordinate pairs. The query
returns pairs that are within the bounds of the polygon. The operator does not query for GeoJSON objects.
To define the polygon, specify an array of coordinate points:
{
<location field>: {
$geoWithin: {
$polygon: [ [ <x1> , <y1> ], [ <x2> , <y2> ], [ <x3> , <y3> ], ... ]
}
}
}
The last point is always implicitly connected to the first. You can specify as many points, i.e. sides, as you like.
Important: If you use longitude and latitude, specify longitude first.
Behavior The $polygon (page 436) operator calculates distances using flat (planar) geometry.
Changed in version 2.2.3: Applications can use $polygon (page 436) without having a geospatial index. However,
geospatial indexes support much faster queries than the unindexed equivalents. Before 2.2.3, a geospatial index must
exist on a field holding coordinates before using any of the geospatial query operators.
Only the 2d geospatial index supports the $polygon (page 436) operator.
Example The following query returns all documents that have coordinates that exist within the polygon defined by
[ 0 , 0 ], [ 3 , 6 ], and [ 6 , 0 ]:
db.places.find(
{
loc: {
$geoWithin: { $polygon: [ [ 0 , 0 ], [ 3 , 6 ], [ 6 , 0 ] ] }
436
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
}
}
)
$uniqueDocs
Definition
$uniqueDocs
Deprecated since version 2.6: Geospatial queries no longer return duplicate results. The $uniqueDocs
(page 437) operator has no impact on results.
Returns a document only once for a geospatial query even if the document matches the query multiple times.
Geospatial Query Compatibility While numerous combinations of query operators are possible, the following
table shows the recommended operators for different types of queries. The table uses the $geoWithin (page 425),
$geoIntersects (page 423) and $near (page 429) operators.
2.3. Operators
437
MongoDB Reference Manual, Release 2.8.0-rc3
Query Document
Geometry of the
Query Condition
Surface Type for
Query Calculation
Units for Query Calculation
Supported by this
Index
polygon
{ $geoWithin : {
$geometry : <GeoJSON Polygon>
} }
sphere
meters
2dsphere
point, line or polygon
{ $geoIntersects : {
$geometry : <GeoJSON>
} }
sphere
meters
2dsphere
point
{ $near : {
$geometry : <GeoJSON Point>,
$maxDistance : d
} }
sphere
meters
2dsphere
The index is required.
rectangle
{ $geoWithin : {
$box : [[x1, y1], [x2, y2]]
} }
flat
flat units
2d
polygon
{ $geoWithin : {
$polygon : [[x1, y1],
[x1, y2],
[x2, y2],
[x2, y1]]
} }
flat
flat units
2d
circular region
{ $geoWithin : {
$center : [[x1, y1], r],
} }
flat
flat units
2d
circular region
{ $geoWithin : {
$centerSphere :
[[x, y], radius]
} }
sphere
radians
2d
2dsphere
point
{ $near : [x1, y1],
$maxDistance : d
}
flat / flat units
flat units
2d
The index is required.
Returns points, lines
and polygons
Returns points only
Array
438
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Query Operator Array
Name
$all (page 439)
$elemMatch
(page 442)
$size (page 443)
Description
Matches arrays that contain all elements specified in the query.
Selects documents if element in the array field matches all the specified $elemMa
(page 442) conditions.
Selects documents if the array field is a specified size.
$all
$all
The $all (page 439) operator selects the documents where the value of a field is an array that contains all the
specified elements. To specify an $all (page 439) expression, use the following prototype:
{ <field>: { $all: [ <value1> , <value2> ... ] } }
Behavior
Equivalent to $and Operation Changed in version 2.6.
The $all (page 439) is equivalent to an $and (page 405) operation of the specified values; i.e. the following
statement:
{ tags: { $all: [ "ssl" , "security" ] } }
is equivalent to:
{ $and: [ { tags: "ssl" }, { tags: "security" } ] }
Nested Array Changed in version 2.6.
When passed an array of a nested array (e.g. [ [ "A" ] ] ), $all (page 439) can now match documents where
the field contains the nested array as an element (e.g. field: [ [ "A" ], ... ]), or the field equals the
nested array (e.g. field: [ "A" ]).
For example, consider the following query 19 :
db.articles.find( { tags: { $all: [ [ "ssl", "security" ] ] } } )
The query is equivalent to:
db.articles.find( { $and: [ { tags: [ "ssl", "security" ] } ] } )
which is equivalent to:
db.articles.find( { tags: [ "ssl", "security" ] } )
As such, the $all (page 439) expression can match documents where the tags field is an array that contains the
nested array [ "ssl", "security" ] or is an array that equals the nested array:
tags: [ [ "ssl", "security" ], ... ]
tags: [ "ssl", "security" ]
This behavior for $all (page 439) allows for more matches than previous versions of MongoDB. Earlier versions
could only match documents where the field contains the nested array.
19 The $all (page 439) expression with a single element is for illustrative purposes since the $all (page 439) expression is unnecessary if
matching only a single element. Instead, when matching a single element, a “contains” expression (i.e. arrayField: element ) is more
suitable.
2.3. Operators
439
MongoDB Reference Manual, Release 2.8.0-rc3
Performance Queries that use the $all (page 439) operator must scan all the documents that match the first element
in the $all (page 439) expression. As a result, even with an index to support the query, the operation may be long
running, particularly when the first element in the $all (page 439) expression is not very selective.
Examples The following examples use the inventory collection that contains the documents:
{
_id: ObjectId("5234cc89687ea597eabee675"),
code: "xyz",
tags: [ "school", "book", "bag", "headphone", "appliance" ],
qty: [
{ size: "S", num: 10, color: "blue" },
{ size: "M", num: 45, color: "blue" },
{ size: "L", num: 100, color: "green" }
]
}
{
_id: ObjectId("5234cc8a687ea597eabee676"),
code: "abc",
tags: [ "appliance", "school", "book" ],
qty: [
{ size: "6", num: 100, color: "green" },
{ size: "6", num: 50, color: "blue" },
{ size: "8", num: 100, color: "brown" }
]
}
{
_id: ObjectId("5234ccb7687ea597eabee677"),
code: "efg",
tags: [ "school", "book" ],
qty: [
{ size: "S", num: 10, color: "blue" },
{ size: "M", num: 100, color: "blue" },
{ size: "L", num: 100, color: "green" }
]
}
{
_id: ObjectId("52350353b2eff1353b349de9"),
code: "ijk",
tags: [ "electronics", "school" ],
qty: [
{ size: "M", num: 100, color: "green" }
]
}
Use $all to Match Values The following operation uses the $all (page 439) operator to query the inventory
collection for documents where the value of the tags field is an array whose elements include appliance, school,
and book:
db.inventory.find( { tags: { $all: [ "appliance", "school", "book" ] } } )
The above query returns the following documents:
440
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
{
_id: ObjectId("5234cc89687ea597eabee675"),
code: "xyz",
tags: [ "school", "book", "bag", "headphone", "appliance" ],
qty: [
{ size: "S", num: 10, color: "blue" },
{ size: "M", num: 45, color: "blue" },
{ size: "L", num: 100, color: "green" }
]
}
{
_id: ObjectId("5234cc8a687ea597eabee676"),
code: "abc",
tags: [ "appliance", "school", "book" ],
qty: [
{ size: "6", num: 100, color: "green" },
{ size: "6", num: 50, color: "blue" },
{ size: "8", num: 100, color: "brown" }
]
}
Use $all with $elemMatch If the field contains an array of documents, you can use the $all (page 439) with
the $elemMatch (page 442) operator.
The following operation queries the inventory collection for documents where the value of the qty field is an
array whose elements match the $elemMatch (page 442) criteria:
db.inventory.find( {
qty: { $all: [
{ "$elemMatch" : { size: "M", num: { $gt: 50} } },
{ "$elemMatch" : { num : 100, color: "green" } }
] }
} )
The query returns the following documents:
{
"_id" : ObjectId("5234ccb7687ea597eabee677"),
"code" : "efg",
"tags" : [ "school", "book"],
"qty" : [
{ "size" : "S", "num" : 10, "color" : "blue" },
{ "size" : "M", "num" : 100, "color" : "blue" },
{ "size" : "L", "num" : 100, "color" : "green" }
]
}
{
"_id" : ObjectId("52350353b2eff1353b349de9"),
"code" : "ijk",
"tags" : [ "electronics", "school" ],
"qty" : [
{ "size" : "M", "num" : 100, "color" : "green" }
]
}
The $all (page 439) operator exists to support queries on arrays. But you may use the $all (page 439) operator to
2.3. Operators
441
MongoDB Reference Manual, Release 2.8.0-rc3
select against a non-array field, as in the following example:
db.inventory.find( { "qty.num": { $all: [ 50 ] } } )
However, use the following form to express the same query:
db.inventory.find( { "qty.num" : 50 } )
Both queries will select all documents in the inventory collection where the value of the num field equals 50.
Note: In most cases, MongoDB does not treat arrays as sets. This operator provides a notable exception to this
approach.
See also:
find() (page 36), update() (page 72), and $set (page 459).
$elemMatch (query)
See also:
$elemMatch (projection) (page 446)
Definition
$elemMatch
The $elemMatch (page 442) operator matches documents in a collection that contain an array field with at
least one element that matches all the specified query criteria.
{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }
Behavior You cannot specify a $where (page 421) expression as a query criterion for $elemMatch (page 442).
Examples
Element Match Given the following documents in the scores collection:
{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }
The following query matches only those documents where the results array contains at least one element that is
both greater than or equal to 80 and is less than 85.
db.scores.find(
{ results: { $elemMatch: { $gte: 80, $lt: 85 } } }
)
The query returns the following document since the element 82 is both greater than or equal to 80 and is less than 85
{ "_id" : 1, "results" : [ 82, 85, 88 ] }
For more information on specifying multiple criteria on array elements, see specify-multiple-criteria-for-arrayelements.
Array of Embedded Documents Given the following documents in the survey collection:
442
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] }
{ _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 } ] }
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }
The following query matches only those documents where the results array contains at least one element with both
product equal to "xyz" and score greater than or equal to 8.
db.survey.find(
{ results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } }
)
Specifically, the query matches the following document:
{ "_id" : 3, "results" : [ { "product" : "abc", "score" : 7 }, { "product" : "xyz", "score" : 8 } ] }
For more information on querying arrays, see read-operations-arrays, including specify-multiple-criteria-for-arrayelements and array-match-embedded-documents sections.
$size
$size
The $size (page 443) operator matches any array with the number of elements specified by the argument. For
example:
db.collection.find( { field: { $size: 2 } } );
returns all documents in collection where field is an array with 2 elements. For instance, the above
expression will return { field: [ red, green ] } and { field: [ apple, lime ] } but
not { field: fruit } or { field: [ orange, lemon, grapefruit ] }. To match fields
with only one element within an array use $size (page 443) with a value of 1, as follows:
db.collection.find( { field: { $size: 1 } } );
$size (page 443) does not accept ranges of values. To select documents based on fields with different numbers
of elements, create a counter field that you increment when you add elements to a field.
Queries cannot use indexes for the $size (page 443) portion of a query, although the other portions of a query
can use indexes if applicable.
Comments
$comment
Definition
$comment
The $comment (page 443) query operator associates a comment to any expression taking a query predicate.
Because comments propagate to the profile (page 366) log, adding a comment can make your profile data
easier to interpret and trace.
The $comment (page 443) operator has the form:
db.collection.find( { <query>, $comment: <comment> } )
Behavior You can use the $comment (page 443) with any expression taking a query predicate, such as the query
predicate in db.collection.update() (page 72) or in the $match (page 490) stage of the aggregation pipeline
(page 564). For an example, see Attach a Comment to an Aggregation Expression (page 444).
2.3. Operators
443
MongoDB Reference Manual, Release 2.8.0-rc3
Examples
Attach a Comment to find The following example adds a $comment (page 443) to a find() (page 36) operation :
db.records.find(
{
x: { $mod: [ 2, 0 ] },
$comment: "Find even values."
}
)
Attach a Comment to an Aggregation Expression
taking a query predicate.
You can use the $comment (page 443) with any expression
The following examples uses the $comment (page 443) operator in the $match (page 490) stage to clarify the
operation:
db.records.aggregate( [
{ $match: { x: { $gt: 0 }, $comment: "Don't allow negative inputs." } },
{ $group : { _id: { $mod: [ "$x", 2 ] }, total: { $sum: "$x" } } }
] )
See also:
$comment (page 555)
Projection Operators
Projection Operators
Name
$ (page 444)
$elemMatch
(page 446)
$meta (page 449)
$slice (page 450)
Description
Projects the first element in an array that matches the query condition.
Projects the first element in an array that matches the specified $elemMatch
(page 446) condition.
Projects the document’s score assigned during $text (page 417) operation.
Limits the number of elements projected from an array. Supports skip and limit slices.
$ (projection)
Definition
$
The positional $ (page 444) operator limits the contents of an <array> from the query results to contain only
the first element matching the query document. To specify an array element to update, see the positional $
operator for updates (page 461).
Use $ (page 444) in the projection document of the find() (page 36) method or the findOne() (page 46)
method when you only need one particular array element in selected documents.
444
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Usage Considerations Both the $ (page 444) operator and the $elemMatch (page 446) operator project a subset
of elements from an array based on a condition.
The $ (page 444) operator projects the array elements based on some condition from the query statement.
The $elemMatch (page 446) projection operator takes an explicit condition argument. This allows you to project
based on a condition not in the query, or if you need to project based on multiple fields in the array’s subdocuments.
See Array Field Limitations (page 445) for an example.
Behavior
Usage Requirements Given the form:
db.collection.find( {
{
db.collection.find( {
{
<array>: <value> ... },
"<array>.$": 1 } )
<array.field>: <value> ...},
"<array>.$": 1 } )
The <array> field being limited must appear in the query document, and the <value> can be documents that
contain query operator expressions (page 400).
Array Field Limitations MongoDB requires the following when dealing with projection over arrays:
• Only one positional $ (page 444) operator may appear in the projection document.
• Only one array field may appear in the query document.
• The query document should only contain a single condition on the array field being projected. Multiple conditions may override each other internally and lead to undefined behavior.
Under these requirements, the following query is incorrect:
db.collection.find( { <array>: <value>, <someOtherArray>: <value2> },
{ "<array>.$": 1 } )
To specify criteria on multiple fields of documents inside that array, use the $elemMatch (page 442) query operator.
The following query will return any subdocuments inside a grades array that have a mean of greater than 70 and a
grade of greater than 90.
db.students.find( { grades: { $elemMatch: {
mean: { $gt: 70 },
grade: { $gt:90 }
} } },
{ "grades.$": 1 } )
You must use the $elemMatch (page 446) operator if you need separate conditions for selecting documents and for
choosing fields within those documents.
Sorts and the Positional Operator When the find() (page 36) method includes a sort() (page 95), the
find() (page 36) method applies the sort() (page 95) to order the matching documents before it applies the
positional $ (page 444) projection operator.
If an array field contains multiple documents with the same field name and the find() (page 36) method includes a
sort() (page 95) on that repeating field, the returned documents may not reflect the sort order because the sort was
applied to the elements of the array before the $ (page 444) projection operator.
Examples
2.3. Operators
445
MongoDB Reference Manual, Release 2.8.0-rc3
Project Array Values A collection students contains the following documents:
{
{
{
{
{
{
"_id"
"_id"
"_id"
"_id"
"_id"
"_id"
:
:
:
:
:
:
1,
2,
3,
4,
5,
6,
"semester"
"semester"
"semester"
"semester"
"semester"
"semester"
:
:
:
:
:
:
1,
1,
1,
2,
2,
2,
"grades"
"grades"
"grades"
"grades"
"grades"
"grades"
:
:
:
:
:
:
[
[
[
[
[
[
70,
90,
85,
79,
88,
95,
In the following query, the projection { "grades.$":
85 for the grades field.
87, 90 ] }
88, 92 ] }
100, 90 ] }
85, 80 ] }
88, 92 ] }
90, 96 ] }
1 } returns only the first element greater than or equal to
db.students.find( { semester: 1, grades: { $gte: 85 } },
{ "grades.$": 1 } )
The operation returns the following documents:
{ "_id" : 1, "grades" : [ 87 ] }
{ "_id" : 2, "grades" : [ 90 ] }
{ "_id" : 3, "grades" : [ 85 ] }
Although the array field grades may contain multiple elements that are greater than or equal to 85, the $ (page 444)
projection operator returns only the first matching element from the array.
Project Array Documents A students collection contains the following documents where the grades field is
an array of documents; each document contain the three field names grade, mean, and std:
{ "_id" : 7, semester: 3, "grades" : [ { grade: 80, mean: 75, std: 8 },
{ grade: 85, mean: 90, std: 5 },
{ grade: 90, mean: 85, std: 3 } ] }
{ "_id" : 8, semester: 3, "grades" : [ { grade: 92, mean: 88, std: 8 },
{ grade: 78, mean: 90, std: 5 },
{ grade: 88, mean: 85, std: 3 } ] }
In the following query, the projection { "grades.$":
than 70 for the grades field:
1 } returns only the first element with the mean greater
db.students.find(
{ "grades.mean": { $gt: 70 } },
{ "grades.$": 1 }
)
The operation returns the following documents:
{ "_id" : 7, "grades" : [
{ "_id" : 8, "grades" : [
{
{
"grade" : 80,
"grade" : 92,
"mean" : 75,
"mean" : 88,
"std" : 8 } ] }
"std" : 8 } ] }
Further Reading $elemMatch (projection) (page 446)
$elemMatch (projection)
See also:
$elemMatch (query) (page 442)
Definition
446
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
$elemMatch
New in version 2.2.
The $elemMatch (page 446) operator limits the contents of an <array> field from the query results to
contain only the first element matching the $elemMatch (page 446) condition.
Usage Considerations Both the $ (page 444) operator and the $elemMatch (page 446) operator project a subset
of elements from an array based on a condition.
The $ (page 444) operator projects the array elements based on some condition from the query statement.
The $elemMatch (page 446) projection operator takes an explicit condition argument. This allows you to project
based on a condition not in the query, or if you need to project based on multiple fields in the array’s subdocuments.
See Array Field Limitations (page 445) for an example.
Examples The examples on the $elemMatch (page 446) projection operator assumes a collection school with
the following documents:
{
_id: 1,
zipcode: "63109",
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 },
{ name: "jeff", school: 108, age: 15 }
]
}
{
_id: 2,
zipcode: "63110",
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
}
{
_id: 3,
zipcode: "63109",
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
}
{
_id: 4,
zipcode: "63109",
students: [
{ name: "barney", school: 102, age: 7 },
{ name: "ruth", school: 102, age: 16 },
]
}
Zipcode Search The following find() (page 36) operation queries for all documents where the value of the
zipcode field is 63109. The $elemMatch (page 446) projection returns only the first matching element of
the students array where the school field has a value of 102:
2.3. Operators
447
MongoDB Reference Manual, Release 2.8.0-rc3
db.schools.find( { zipcode: "63109" },
{ students: { $elemMatch: { school: 102 } } } )
The operation returns the following documents:
{ "_id" : 1, "students" : [ { "name" : "john", "school" : 102, "age" : 10 } ] }
{ "_id" : 3 }
{ "_id" : 4, "students" : [ { "name" : "barney", "school" : 102, "age" : 7 } ] }
• For the document with _id equal to 1, the students array contains multiple elements with the school field
equal to 102. However, the $elemMatch (page 446) projection returns only the first matching element from
the array.
• The document with _id equal to 3 does not contain the students field in the result since no element in its
students array matched the $elemMatch (page 446) condition.
$elemMatch with Multiple Fields The $elemMatch (page 446) projection can specify criteria on multiple
fields:
The following find() (page 36) operation queries for all documents where the value of the zipcode field is 63109.
The projection includes the first matching element of the students array where the school field has a value of
102 and the age field is greater than 10:
db.schools.find( { zipcode: "63109" },
{ students: { $elemMatch: { school: 102, age: { $gt: 10} } } } )
The operation returns the three documents that have zipcode equal to 63109:
{ "_id" : 1, "students" : [ { "name" : "jess", "school" : 102, "age" : 11 } ] }
{ "_id" : 3 }
{ "_id" : 4, "students" : [ { "name" : "ruth", "school" : 102, "age" : 16 } ] }
The document with _id equal to 3 does not contain the students field since no array element matched the
$elemMatch (page 446) criteria.
$elemMatch with sort() When the find() (page 36) method includes a sort() (page 95), the find()
(page 36) method applies the sort() (page 95) to order the matching documents before it applies the projection.
This is a general rule when sorting and projecting, and is discussed in Interaction with Projection (page 97).
If an array field contains multiple documents with the same field name and the find() (page 36) method includes a
sort() (page 95) on that repeating field, the returned documents may not reflect the sort order because the sort()
(page 95) was applied to the elements of the array before the $elemMatch (page 446) projection.
An array’s sorting value is taken from either its “minimum” or “maximum” value, depending on which way the sorting
goes. The way that sort() (page 95) sorts documents containing arrays is described in Ascending/Descending Sort
(page 96).
The following query includes a sort() (page 95) to order by descending students.age field:
db.schools.find(
{ zipcode: "63109" },
{ students: { $elemMatch: { school: 102 } } }
).sort( { "students.age": -1 } )
The operation applies the sort() (page 95) to order the documents that have the field zipcode equal to 63109
and then applies the projection. The operation returns the three documents in the following order:
448
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
{ "_id" : 4, "students" : [ { "name" : "barney", "school" : 102, "age" : 7 } ] }
{ "_id" : 1, "students" : [ { "name" : "john", "school" : 102, "age" : 10 } ] }
{ "_id" : 3 }
Even though the sort is descending, the younger student is listed first. This is because the sort occurred before the
older students in Barney’s document were projected out.
See also:
$ (projection) (page 444) operator
$meta
$meta
New in version 2.6.
The $meta (page 449) projection operator returns for each matching document the metadata (e.g.
"textScore") associated with the query.
A $meta (page 449) expression has the following syntax:
{ $meta: <metaDataKeyword> }
The $meta (page 449) expression can specify the following keyword as the <metaDataKeyword>:
Keyword
Description
"textScore"
Returns the score associated with the corresponding $text (page 417) query for each
matching document. The text score signifies how well the document matched the
stemmed term or terms. If not used in conjunction with a $text (page 417) query,
returns a score of 0.
Sort
Order
Descending
Behaviors The $meta (page 449) expression can be a part of the projection document as well as a sort()
(page 95) expression as:
{ <projectedFieldName>: { $meta: "textScore" } }
Projected Field Name The <projectedFieldName> cannot include a dot (.) in the name.
If the specified <projectedFieldName> already exists in the matching documents, in the result set, the existing
fields will return with the $meta (page 449) values instead of with the stored values.
Projection The $meta (page 449) expression can be used in the projection document, as in:
db.collection.find(
<query>,
{ score: { $meta: "textScore" } }
)
The $meta (page 449) expression specifies the inclusion of the field to the result set and does not specify the exclusion
of the other fields.
The $meta (page 449) expression can be a part of a projection document that specifies exclusions of other fields or
that specifies inclusions of other fields.
The metadata returns information on the processing of the <query> operation. As such, the returned metadata, assigned to the <projectedFieldName>, has no meaning inside a <query> expression; i.e. specifying a condition
2.3. Operators
449
MongoDB Reference Manual, Release 2.8.0-rc3
on the <projectedFieldName> as part of the <query> is similar to specifying a condition on a non-existing
field if no field exists in the documents with the <projectedFieldName>.
Sort The $meta (page 449) expression can be part of a sort() (page 95) expression, as in:
db.collection.find(
<query>,
{ score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )
To include a $meta (page 449) expression in a sort() (page 95) expression, the same $meta (page 449) expression, including the <projectedFieldName>, must appear in the projection document. The specified metadata
determines the sort order. For example, the "textScore" metadata sorts in descending order.
For additional examples, see Text Search with Additional Query and Sort Expressions (page 420).
Examples For examples of "textScore" projections and sorts, see $text (page 417).
$slice (projection)
$slice
The $slice (page 450) operator controls the number of items of an array that a query returns. For information
on limiting the size of an array during an update with $push (page 470), see the $slice (page 474) modifier
instead.
Consider the following prototype query:
db.collection.find( { field: value }, { array: {$slice: count } } );
This operation selects the document collection identified by a field named field that holds value and
returns the number of elements specified by the value of count from the array stored in the array field. If
count has a value greater than the number of elements in array the query returns all elements of the array.
$slice (page 450) accepts arguments in a number of formats, including negative values and arrays. Consider
the following examples:
db.posts.find( {}, { comments: { $slice: 5 } } )
Here, $slice (page 450) selects the first five items in an array in the comments field.
db.posts.find( {}, { comments: { $slice: -5 } } )
This operation returns the last five items in array.
The following examples specify an array as an argument to $slice (page 450). Arrays take the form of [
skip , limit ], where the first value indicates the number of items in the array to skip and the second
value indicates the number of items to return.
db.posts.find( {}, { comments: { $slice: [ 20, 10 ] } } )
Here, the query will only return 10 items, after skipping the first 20 items of that array.
db.posts.find( {}, { comments: { $slice: [ -20, 10 ] } } )
This operation returns 10 items as well, beginning with the item that is 20th from the last item of the array.
450
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
2.3.2 Update Operators
The following modifiers are available for use in update operations; e.g. in db.collection.update() (page 72)
and db.collection.findAndModify() (page 42).
Update Operators
Fields
Field Update Operators
Name
$currentDate
(page 451)
$inc (page 452)
$max (page 453)
$min (page 454)
$mul (page 456)
$rename
(page 457)
$setOnInsert
(page 458)
$set (page 459)
$unset
(page 461)
Description
Sets the value of a field to current date, either as a Date or a Timestamp.
Increments the value of the field by the specified amount.
Only updates the field if the specified value is greater than the existing field value.
Only updates the field if the specified value is less than the existing field value.
Multiplies the value of the field by the specified amount.
Renames a field.
Sets the value of a field if an update results in an insert of a document. Has no effect
update operations that modify existing documents.
Sets the value of a field in a document.
Removes the specified field from a document.
$currentDate
Definition
$currentDate
The $currentDate (page 451) operator sets the value of a field to the current date, either as a Date or a
timestamp. The default type is Date.
The $currentDate (page 451) operator has the form:
{ $currentDate: { <field1>: <typeSpecification1>, ... } }
<typeSpecification> can be either:
•a boolean true to set the field value to the current date as a Date, or
•a document { $type: "timestamp" } or { $type: "date" } which explicitly specifies the
type. The operator is case-sensitive and accepts only the lowercase "timestamp" or the lowercase
"date".
To specify a <field> in an embedded document or in an array, use dot notation.
Behavior If the field does not exist, $currentDate (page 451) adds the field to a document.
Example Consider the following document in the users collection:
{ _id: 1, status: "a", lastModified: ISODate("2013-10-02T01:11:18.965Z") }
2.3. Operators
451
MongoDB Reference Manual, Release 2.8.0-rc3
The following operation updates the lastModified field to the current date, the��”cancellation.date”�� field to the
current timestamp as well as updating the status field to "D" and the "cancellation.reason" to "user
request".
db.users.update(
{ _id: 1 },
{
$currentDate: {
lastModified: true,
"cancellation.date": { $type: "timestamp" }
},
$set: {
status: "D",
"cancellation.reason": "user request"
}
}
)
The updated document would resemble:
{
"_id" : 1,
"status" : "D",
"lastModified" : ISODate("2014-09-17T23:25:56.314Z"),
"cancellation" : {
"date" : Timestamp(1410996356, 1),
"reason" : "user request"
}
}
See also:
db.collection.update() (page 72), db.collection.findAndModify() (page 42)
$inc
Definition
$inc
The $inc (page 452) operator increments a field by a specified value and has the following form:
{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
To specify a <field> in an embedded document or in an array, use dot notation.
Behavior The $inc (page 452) operator accepts positive and negative values.
If the field does not exist, $inc (page 452) creates the field and sets the field to the specified value.
Use of the $inc (page 452) operator on a field with a null value will generate an error.
$inc (page 452) is an atomic operation within a single document.
Example Consider a collection products with the following document:
{
_id: 1,
sku: "abc123",
452
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
quantity: 10,
metrics: {
orders: 2,
ratings: 3.5
}
}
The following update() (page 72) operation uses the $inc (page 452) operator to decrease the quantity field
by 2 (i.e. increase by -2) and increase the "metrics.orders" field by 1:
db.products.update(
{ sku: "abc123" },
{ $inc: { quantity: -2, "metrics.orders": 1 } }
)
The updated document would resemble:
{
"_id" : 1,
"sku" : "abc123",
"quantity" : 8,
"metrics" : {
"orders" : 3,
"ratings" : 3.5
}
}
See also:
db.collection.update() (page 72), db.collection.findAndModify() (page 42)
$max
Definition
$max
The $max (page 453) operator updates the value of the field to a specified value if the specified value is greater
than the current value of the field. The $max (page 453) operator can compare values of different types, using
the BSON comparison order.
The $max (page 453) operator expression has the form:
{ $max: { <field1>: <value1>, ... } }
To specify a <field> in an embedded document or in an array, use dot notation.
Behavior If the field does not exists, the $max (page 453) operator sets the field to the specified value.
Examples
Use $max to Compare Numbers Consider the following document in the collection scores:
{ _id: 1, highScore: 800, lowScore: 200 }
The highScore for the document currently has the value 800. The following operation uses $max (page 558) to
compare the 800 and the specified value 950 and updates the value of highScore to 950 since 950 is greater than
800:
2.3. Operators
453
MongoDB Reference Manual, Release 2.8.0-rc3
db.scores.update( { _id: 1 }, { $max: { highScore: 950 } } )
The scores collection now contains the following modified document:
{ _id: 1, highScore: 950, lowScore: 200 }
The next operation has no effect since the current value of the field highScore, i.e. 950, is greater than 870:
db.scores.update( { _id: 1 }, { $max: { highScore: 870 } } )
The document remains unchanged in the scores collection:
{ _id: 1, highScore: 950, lowScore: 200 }
Use $max to Compare Dates Consider the following document in the collection tags:
{
_id: 1,
desc: "crafts",
dateEntered: ISODate("2013-10-01T05:00:00Z"),
dateExpired: ISODate("2013-10-01T16:38:16.163Z")
}
The following operation compares the current value of the dateExpired field,
i.e.
ISODate("2013-10-01T16:38:16.163Z"), with the specified date new Date("2013-09-30") to
determine whether to update the field:
db.tags.update(
{ _id: 1 },
{ $max: { dateExpired: new Date("2013-09-30") } }
)
The operation does not update the dateExpired field:
{
_id: 1,
desc: "decorative arts",
dateEntered: ISODate("2013-10-01T05:00:00Z"),
dateExpired: ISODate("2013-10-01T16:38:16.163Z")
}
See also:
db.collection.update() (page 72), db.collection.findAndModify() (page 42)
$min
Definition
$min
The $min (page 454) updates the value of the field to a specified value if the specified value is less than the
current value of the field. The $min (page 454) operator can compare values of different types, using the BSON
comparison order.
{ $min: { <field1>: <value1>, ... } }
To specify a <field> in an embedded document or in an array, use dot notation.
454
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Behavior If the field does not exists, the $min (page 454) operator sets the field to the specified value.
Examples
Use $min to Compare Numbers Consider the following document in the collection scores:
{ _id: 1, highScore: 800, lowScore: 200 }
The lowScore for the document currently has the value 200. The following operation uses $min (page 454) to
compare 200 to the specified value 150 and updates the value of lowScore to 150 since 150 is less than 200:
db.scores.update( { _id: 1 }, { $min: { lowScore: 150 } } )
The scores collection now contains the following modified document:
{ _id: 1, highScore: 800, lowScore: 150 }
The next operation has no effect since the current value of the field lowScore, i.e 150, is less than 200:
db.scores.update( { _id: 1 }, { $min: { lowScore: 250 } } )
The document remains unchanged in the scores collection:
{ _id: 1, highScore: 800, lowScore: 150 }
Use $min to Compare Dates Consider the following document in the collection tags:
{
_id: 1,
desc: "crafts",
dateEntered: ISODate("2013-10-01T05:00:00Z"),
dateExpired: ISODate("2013-10-01T16:38:16Z")
}
The following operation compares the current value of the dateEntered field,
i.e.
ISODate("2013-10-01T05:00:00Z"), with the specified date new Date("2013-09-25") to determine whether to update the field:
db.tags.update(
{ _id: 1 },
{ $min: { dateEntered: new Date("2013-09-25") } }
)
The operation updates the dateEntered field:
{
_id: 1,
desc: "crafts",
dateEntered: ISODate("2013-09-25T00:00:00Z"),
dateExpired: ISODate("2013-10-01T16:38:16Z")
}
See also:
db.collection.update() (page 72), db.collection.findAndModify() (page 42)
$mul
2.3. Operators
455
MongoDB Reference Manual, Release 2.8.0-rc3
Definition
$mul
New in version 2.6.
Multiply the value of a field by a number. To specify a $mul (page 456) expression, use the following prototype:
{ $mul: { field: <number> } }
The field to update must contain a numeric value.
To specify a <field> in an embedded document or in an array, use dot notation.
Behavior If the field does not exist in a document, $mul (page 456) creates the field and sets the value to zero of
the same numeric type as the multiplier.
Multiplication with values of mixed numeric types (32-bit integer, 64-bit integer, float) may result in conversion of
numeric type. See Multiplication Type Conversion Rules for details.
$mul (page 456) is an atomic operation within a single document.
Examples
Multiply the Value of a Field Consider a collection products with the following document:
{ _id: 1, item: "ABC", price: 10.99 }
The following db.collection.update() (page 72) operation updates the document, using the $mul (page 456)
operator to multiply the value in the price field by 1.25:
db.products.update(
{ _id: 1 },
{ $mul: { price: 1.25 } }
)
The operation results in the following document, where the new value of the price field 13.7375 reflects the
original value 10.99 multiplied by 1.25:
{ _id: 1, item: "ABC", price: 13.7375 }
Apply $mul Operator to a Non-existing Field Consider a collection products with the following document:
{ _id: 2,
item: "Unknown" }
The following db.collection.update() (page 72) operation updates the document, applying the $mul
(page 456) operator to the field price that does not exist in the document:
db.products.update(
{ _id: 2 },
{ $mul: { price: NumberLong(100) } }
)
The operation results in the following document with a price field set to value 0 of numeric type shell-type-long, the
same type as the multiplier:
{ "_id" : 2, "item" : "Unknown", "price" : NumberLong(0) }
456
Chapter 2. Interfaces Reference
MongoDB Reference Manual, Release 2.8.0-rc3
Multiply Mixed Numeric Types Consider a collection products with the following document:
{ _id: 3,
item: "XYZ", price: NumberLong(10) }
The following db.collection.update() (page 72) operation uses the $mul (page 456) operator to multiply
the value in the price field NumberLong(10) by NumberInt(5):
db.products.update(
{ _id: 3 },
{ $mul: { price: NumberInt(5) } }
)
The operation results in the following document:
{ "_id" : 3, "item" : "XYZ", "price" : NumberLong(50) }
The value in the price field is of type shell-type-long. See Multiplication Type Conversion Rules for details.
See also:
db.collection.update() (page 72), db.collection.findAndModify() (page 42)
$rename
Definition
$rename
The $rename (page 457) operator updates the name of a field and has the following form:
{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }
The new field name must differ from the existing field name. To specify a <field> in an embedded document,
use dot notation.
Consider the following example:
db.students.update( { _id: 1 }, { $rename: { 'nickname': 'alias', 'cell': 'mobile' } } )
This operation renames the field nickname to alias, and the field cell to mobile.
Behavior The $rename (page 457) operator logically performs an $unset (page 461) of both the old name and
the new name, and then performs a $set (page 459) operation with the new name. As such, the operation may not
preserve the order of the fields in the document; i.e. the renamed field may move within the document.
If the document already has a field with the <newName>, the $rename (page 457) operator removes that field and
renames the specified <field> to <newName>.
If the field to rename does not exist in a document, $rename (page 457) does nothing (i.e. no operation).
For fields in embedded documents, the $rename (page 457) operator can rename these fields as well as move the
fields in and out of embedded documents. $rename (page 457) does not work if these fields are in array elements.
Examples A collection students the following document where a field nmae appears misspelled, i.e. should be
name:
{ "_id": 1,
"alias": [ "The American Cincinnatus", "The American Fabius" ],
"mobile": "555-555-5555",
2.3. Operators
457
MongoDB Reference Manual, Release 2.8.0-rc3
"nmae": { "first" : "george", "last" : "washington" }
}
The examples in this section successively updates this document.
Rename a Field To rename a field, call the $rename (page 457) operator with the current name of the field and the
new name:
db.students.update( { _id: 1 }, { $rename: { "nmae": "name" } } )
This operation renames the field nmae to n