Doc Index

Space Index

0-9 ... 8 A ... 29 B ... 22 C ... 46 D ... 32 E ... 8
F ... 9 G ... 12 H ... 11 I ... 18 J ... 12 K ... 6
L ... 8 M ... 40 N ... 4 O ... 13 P ... 15 Q ... 8
R ... 40 S ... 38 T ... 15 U ... 13 V ... 9 W ... 12
X ... 0 Y ... 1 Z ... 0 !@#$ ... 0    

0-9

1.0 Changelist
Wrote MongoDB. See documentation
1.1 Development Cycle
1.2.x Release Notes
New Features More indexes per collection Faster index creation Map/Reduce Stored JavaScript functions Configurable fsync time Several small features and fixes DB Upgrade Required There are some changes that will require doing an upgrade ...
1.4 Release Notes
We're pleased to announce the 1.4 release of MongoDB. 1.4 is a drop in replacement for 1.2. To upgrade you just need to shutdown mongod, then restart with the new binaries. (Users upgrading from release 1.0 should review the 1.2 release notes 1.2.x ...
1.6 Release Notes
MongoDB 1.6 is a dropin replacement for 1.4. To upgrade, simply shutdown {{mongod}} then restart with the new binaries. MongoDB v1.8 DOCS:1.8 Release Notes is now available. \ Please note that you should upgrade to the latest version of whichever driver you're ...
1.8 Release Notes
MongoDB 1.8 is a dropin replacement for 1.6, except: replica set nodes should be upgraded in a particular order Upgrading to 1.8. The options to the Map/Reduce command have changed in 1.8, causing incompatibility with previous releases. If you use MapReduce, please ...
2.0 Release Notes
Upgrading Although the major version number has changed, MongoDB 2.0 is a standard, incremental production release and works as a dropin replacement for MongoDB 1.8. However, there are a few changes you must be aware of before attempting to upgrade: # If you create new ...
2.2 Release Notes
Upgrading Here is how. What's New Many things. Major Features Aggregation Framework Docs Aggregation Framework MongoDB 2.2 is the first release with the aggregation framework TTL Collections http://jira.mongodb.org/browse/SERVER211 Concurrency improvements DB Level Locking ...

A

A Sample Configuration Session
following example uses two shards (each with a single mongod process), one config db, and one mongos process, all running on a single test server. In addition to the script below, a python script for starting and configuring shard components on a single ...
About
About the local database
mongod}} reserves the database {{local}} for special functionality. It is special in that its contents are never replicated. When authentication is used, authenticating Security and Authentication against the {{local}} database is equivalent to authenticating against the {{admin}} database: it gives you permissions across all ...
Adding a New Set Member
Adding a new member to an existing replica set is easy. The new member should either have an empty data directory or a recent copy of the data from another set member. When starting {{mongod}} on the new server, provide ...
Adding an Arbiter
Arbiters are nodes in a replica set that only participate in elections: they don't have a copy of the data and will never become the primary node (or even a readable secondary). They are mainly useful for breaking ties during elections (e.g. if a set only has two members ...
Admin UIs
MongoDB does not include a GUIstyle administrative interface. Instead most administration is done from command line tools such as the mongo shell. However some UI's are available as separate community projects and are listed below. Some are focused on administration, while some ...
Admin Zone
Community AdminRelated Articles boxedice.com notes from a production deployment http://blog.boxedice.com/2010/02/28/notesfromaproductionmongodbdeployment/ Survey of Admin UIs for MongoDB http://blog.timgourley.com/post/453680012/tuesdaynighttechmongodbuiedition MongoDB Nagios Check http://tag1consulting.com/blog/mongodbnagioscheck MongoDB Cacti Graphs http://tag1consulting.com ...
Advanced Queries
MongoDB, just like in an RDBMS, creating appropriate indexes for queries is quite important for performance. See the Indexes page for more info. Intro MongoDB offers a rich query environment with lots of features. This page lists some of those features ...
Aggregation
Mongo includes utility functions which provide serverside {{count, distinct,}} and {{group by}} operations.  More advanced aggregate functions can be crafted using MapReduce http://www.mongodb.org/display/DOCS/MapReduce. Aggregation Framework v2.2\ This is a new module ...
Aggregation Framework
Aggregation Framework was first available in MongoDB 2.1.0. See an improved version of this documentation in the MongoDB Manual http://docs.mongodb.org/manual: Aggregation Documentation http://docs.mongodb.org/manual/applications/aggregation/ Aggregation Framework Operators http://docs.mongodb.org/manual/reference ...
Aggregation Framework - $group
Overview In its most general form, $group is used to group documents together for the purpose of calculating an aggregate value based on their content. In practical terms, this could be something like calculating the average number of page views for each web page ...
Aggregation Framework - $limit
Overview The $limit pipeline operator limits the number of JSON documents that passes through it. Specification $limit takes a single numeric value as a parameter. Once that many documents have passed through the pipeline operator, no more will. Here's a simple example: db.article.aggregate ...
Aggregation Framework - $match
Overview $match filters documents. Documents which do not match the specified predicate are filtered out and do not progress further along the aggregation pipeline. Documents which do match are passed along unchanged. Specification $match predicate syntax is always ...
Aggregation Framework - $project
Overview $project can be used to reshape a document stream by renaming fields, adding fields, or removing fields. Specification For the examples that follow, imagine an article collection made up of documents that look like this: { title : "this is my title" , author : "bob ...
Aggregation Framework - $skip
Overview The $skip pipeline operator skips over a number of JSON documents before passing on the rest of its input. Specification $skip takes a single numeric value as a parameter. Once that many input documents have been skipped, the rest are passed ...
Aggregation Framework - $sort
Overview The $sort pipeline operator sorts its input documents. Specification db.<collectionname>.aggregate( { $sort : } ); $sort requires a sort key. Sort key specifications are exactly the same as those for indexing (see Indexes Basics Indexes#IndexesBasics and Indexes ...
Aggregation Framework - $unwind
Overview $unwind peels off the elements of an array one by one, returning a stream of documents. For each source document, for each member of the specified array within it, a new document emerges, but with the specified array replaced by one of its elements. Specification ...
Aggregation Framework - Expression Reference
Overview Expressions are used to calculate values from fields and other values. Expressions are expressed in a prefix form as JSON fieldvalue pairs. The "fieldname" is really the expression name. Multiple operands are then provided in an array: $add:\5, 6, 7\. Most ...
Alerts
page lists critical alerts and advisories for MongoDB. This page is a work in progress and will be enhanced over time. See http://jira.mongodb.org/ for a comprehensive list of bugs and feature requests. Data Integrity Related Documents may be missing on a replication secondary after initial ...
Amazon EC2
MongoDB runs well on Amazon EC2 http://aws.amazon.com/ec2/. This page includes some notes in this regard. Getting Started on EC2 This guide Amazon EC2 Quickstart is intended to provide instructions on using the MongoDB AMI to set up production instances ...
Amazon EC2 Quickstart
guide is intended to provide instructions on setting up production instances of MongoDB across Amazon's Web Services (AWS) EC2 infrastructure. First, we'll step through deployment planning (instance specifications, deployment size, etc.) and then we'll set up ...
Architecture and Components
list of the components (processes) in the MongoDB server package. mongod The core database process DOCS:Starting and Stopping Mongo mongos Sharding DOCS:Sharding controller mongo The database shell DOCS:mongo The Interactive Shell (uses interactive javascript) DOCS ...
Articles
See also the User Feedback DOCS:User Feedback page for community presentations, blog posts, and more. Best of the MongoDB Blog What is the Right Data Model? http://blog.mongodb.org/post/142940558/whatistherightdatamodel \ (for nonrelational databases) Why Schemaless is Good http://blog.mongodb.org ...
Atomic operation examples
key goal of MongoDB is to handle a good breadth of use cases, and to handle in a way that is easy for the developer. We found that a good number of use cases require atomic operations / strong consistency; thus that is a feature of the product. Below are some examples (in mongo ...
Atomic Operations
MongoDB supports atomic operations on single documents.&nbsp; MongoDB does not support traditional locking and complex transactions for a number of reasons: First, in sharded environments, distributed locks could be expensive and slow.&nbsp; Mongo DB's goal is to be lightweight and fast ...
Automating Deployment with CloudFormation
CloudFormation http://aws.amazon.com/cloudformation/ from Amazon Web Services provides an easy mechanism to create and manage a collection of AWS resources. To use CloudFormation you create and deploy a template which describes the resources in your stack via the AWS ...
AWS Marketplace
you installed MongoDB via the AWS Marketplace, refer to the sections below to get up and running with your EC2 instance. If you are interested in using the instance for development purposes, check out #Development Instance below. If you are interested in creating a production ...
Azure Configuration
following are the configuration operations available as part of the MongoDB Replica Sets Azure package. ReplicaSetRole configuration Configuration Instance count \ Set to the number of replica set members you require. Default is 3. Setting this to 1 would run a replica set ...
Azure Deployment
development environment The solution can be built and run in a development environment using the Azure emulators as is using Visual Studio 2010 (if adequate disk space is available). Since this solution uses Cloud Drive you cannot run from a development environment ...

B

Backing Up Sharded Cluster
See also Backups DOCS:Backups and Import Export Tools DOCS:Import Export Tools for more information on backups, particularly on the step of backing up each individual server. If you are on EC2 you should look at EC2 Backup & Restore ...
Backups
Several strategies exist for backing up MongoDB databases.&nbsp; A word of warning: if you do not have journaling enabled, then it's not safe to simply copy the mongod data files (by default in /data/db/) while the database is running and writes are occurring; such a backup ...
Benchmarks
MongoDB does not publish any official benchmarks. We recommend running application performance tests on your application's workload to find bottleneck and for performance tuning. See Also DOCS:JS Benchmarking Harness
Books
mongodbinaction.png! http://manning.com/banker !sagya.png! https://www.amazon.de/MongoDBSagJazuNoSQL/dp/3868020578/ref=sr13?ie=UTF8&qid=1291985616&sr=83 !mongodbcover.png! http://openmymind.net/2011/3/28/TheLittleMongoDBBook !packt.jpg! http://link.packtpub.com/2qxi08 You can download samples at 10gen.com/books ...
Boost 1.41.0 Visual Studio 2010 Binary
OLD and was for the VS2010 BETA. See the new Boost and Windows page instead. The following is a prebuilt boost http://www.boost.org/ binary (libraries) for Visual Studio 2010 beta 2. The MongoDB vcxproj files assume this package is unzipped under c:\Program ...
Boost and Windows
Visual Studio 2010 Prebuilt from mongodb.org Click here http://www.mongodb.org/pages/viewpageattachments.action?pageId=12157032 for a prebuilt boost library for Visual Studio 2010.&nbsp; 7zip http://www.7zip.org/ format. Building Yourself Download the boost source ...
BSON
bsonspec.org http://www.bsonspec.org/ BSON is a bin­aryen­coded seri­al­iz­a­tion of JSONlike doc­u­ments. BSON is designed to be lightweight, traversable, and efficient. BSON, like JSON, supports the embedding of objects and arrays within other objects ...
BSON Arrays in C++
examples using namespace mongo; using namespace bson; bo anobj; / transform a BSON array into a vector of BSONElements. we match array # positions with their vector position, and ignore any fields with nonnumeric field names. / vector<be> a = anobj"x".Array ...
Building
Note: see the Downloads DOCS:Downloads page for prebuilt binaries, it's recommended to use those as all full QA occurs after those are built. This section provides instructions on setting up your environment to write Mongo drivers or other infrastructure ...
Building Boost
necessary when building mongo versions 2.1.1 or later. MongoDB uses the www.boost.org Boost C\ libraries. Windows See also the prebuilt libraries http://www.mongodb.org/pages/viewpageattachments.action?pageId=12157032 page. By default c:\boost\ is checked for the boost ...
Building for FreeBSD
FreeBSD 8.0 and later, there is a mongodb port you can use. For FreeBSD <= 7.2: # Get the database source: http://www.github.com/mongodb/mongo. # Update your ports tree: $ sudo portsnap fetch && portsnap extract The packages that come by default on 7.2 ...
Building for Linux
Note: Binaries are available for most platforms. Most users won't need to compile mongo themselves; in addition every prebuilt binary has been regression tested. See the Downloads page for these prebuilt binaries. These instructions apply to the git master branch ...
Building for OS X
set up your OS X computer for MongoDB development: Prerequisites Xcode Available in the App Store. You only need to get the command line tools, if you don't want to install the whole IDE. SCons SCons is the build tool ...
Building for Solaris
MongoDB server currently supports little endian Solaris operation.&nbsp; (Although most drivers not the database server work on both.) Community: Help us make this rough page better please\!&nbsp; (And help us add support for big ...
Building for Windows
Binaries are available for most platforms. Most users won't need to compile mongo themselves; in addition every prebuilt binary has been regression tested. See the Downloads page for these prebuilt binaries. MongoDB can be compiled for Windows (32 and 64 ...
Building indexes with replica sets
Version 2.1.0 and later Indexes can be built in the foreground or background. Background indexes builds on the primary will result in background index builds on the secondaries. Index built on primary Index built on secondary Index built on recovering member Foreground Foreground Foreground ...
Building Spider Monkey
MongoDB uses SpiderMonkey http://www.mozilla.org/js/spidermonkey/ for serverside Javascript execution. Pre v2.0: MongoDB requires a js.lib file when linking. This page details how to build js.lib. v2.0: this is handled automatically by the Mongo build scripts via ...
Building SpiderMonkey
Building the Mongo Shell on Windows
You can build the mongo shell with either scons or a Visual Studio 2010 project file. Scons scons mongo.exe Visual Studio 2010 Project File A VS2010 vcxproj file is availabe for building the shell. From the mongo directory open ...
Building with V8
Linux or OSX $ pwd /mongo $ cd .. $ svn checkout http://v8.googlecode.com/svn/trunk/ v8 $ cd v8 $ scons arch=x64 debuggersupport=off snapshot=off profilingsupport=off $ cd ../mongo $ scons usev8 Windows $ pwd /mongo ...
Building with Visual Studio 2008
instructions are for versions of mongo prior to 2.1.1. For version 2.1.1 and newer, the instructions for Visual Studio 2010 DOCS:Building with Visual Studio 2010 and Visual Studo 2008 are the same. MongoDB can be compiled for Windows (32 and 64 bit) using Visual ...
Building with Visual Studio 2010
Binaries are available for most platforms. Most users won't need to compile mongo themselves; in addition every prebuilt binary has been regression tested. See the Downloads page for these prebuilt binaries. v2.1.1 MongoDB can be compiled for Windows (32 ...

C

C Language Center
C Driver {}The MongoDB C Driver is the 10gensupported driver for MongoDB. It's written in pure C. The driver's core API is stable as of the v0.4 release; however, the GridFS API may change somewhat in the v0.5 release. Primary Doc Page http://api.mongodb.org ...
C Sharp Language Center
C++ BSON Library
MongoDB C driver library includes a bson package that implements the BSON specification (see http://www.bsonspec.org/). This library can be used standalone for object serialization and deserialization even when one is not using MongoDB at all. Include {{bson/bson.h}} or {{db ...
C++ Driver Compiling and Linking
C\ driver is included in the MongoDB server source repository, and can also be downloaded as a separate, "standalone" tarball (see Docs:downloads). &nbsp; To compile the "standalone" C\ driver, run the scons command in the toplevel directory of the driver sources, e.g.: cd ...
C++ Driver Download
Driver tarballs The C client library can be found at http://dl.mongodb.org/dl/cxxdriver/. Note: despite the word 'linux' in the filenames, these files are mostly source code and thus should be applicable to all operating systems. From the server source code ...
C++ getLastError
string mongo::DBClientWithCommands::getLastError() http://api.mongodb.org/cplusplus/1.9.0pre/classmongo11dbclientwithcommands.html#5ad5855d5be74bc144d443f00927340d; Get error result from the last operation on this connection. Empty string if no error. BSONObj DBClientWithCommands::getLastErrorDetailed(); Get the full last error object. See the DOCS:getLastError ...
C++ Language Center
C\ driver is available for communicating with the MongoDB.&nbsp; As the database is written in C, the driver actually uses some core MongoDB code \\ this is the same driver that the database uses itself for replication. The driver has been compiled successfully on Linux, OS X ...
C++ Tutorial
document is an introduction to usage of the MongoDB database from a C\ program. First, install Mongo \\ see the Quickstart for details. Next, you may wish to take a look at the Developer's Tour DOCS:MongoDB A Developer's Tour guide for a language independent ...
Caching
Memory Mapped Storage Engine This is the current storage engine for MongoDB, and it uses memorymapped files for all disk I/O.&nbsp; Using this strategy, the operating system's virtual memory manager is in charge of caching.&nbsp; This has several implications: There is no redundancy ...
Capped Collections
Capped collections are fixed sized collections that have a very high performance autoFIFO ageout feature (age out is based on insertion order). They are a bit like the "RRD" concept if you are familiar with that. In addition, capped collections automatically, with high performance, maintain ...
CentOS and Fedora Packages
10gen publishes yuminstallable RPM packages that for x86 and x8664 platforms. The packages are named mongo10gen and mongo10genserver for production releases (versions with even middle numbers), and mongo10genunstable and mongo10genunstableserver for development releases (odd middle version numbers, except for some release candidates ...
Changing a Shard Key
automatic support for changing the shard key for a collection. In addition this would fundamentally be a very expensive operation most of the data in the cluster for the collection likely moves from machine to machine. Thus it is very important to choose the right shard key DOCS:Choosing ...
Changing Config Servers
Sections: The config server data is the most important data in your entire cluster. Back it up before doing config server maintenance. Adding and changing config servers is a bit tricky right now. This will be improved in a future release, see http ...
Checking Server Memory Usage
How Caching Works See Caching Memory Mapped Files Depending on the platform you may see the mapped files as memory in the process (see the Virtual Memory section below), but this is not strictly correct. If mapped files are counted as process memory, the {{top ...
Choosing a Shard Key
important to choose the right shard key for a collection. If the collection is gigantic it is difficult to change the key later. When in doubt please ask for suggestions in the support forums or IRC. The basic rule of thumb is : whatever field is common to most of your queries, that field ...
cloneCollection Command
Copy a single collection from one server to another. db.runCommand( ); Copies a collection from one server to another. Do not use on a single server as the destination is placed at the same {{db.collection}} (namespace) as the source. The local copy of the namespace is emptied before the copying ...
Collections
MongoDB collections are essentially named groupings of documents. You can think of them as roughly equivalent to relational database tables. Overview A MongoDB collection is a collection of BSON BSON documents. These documents usually have the same structure, but this is not a requirement since MongoDB ...
collStats Command
Statistics on a collection. The command name is "collStats" and the shell helper is database.collection.stats(). > db.commandHelp("collStats") help for: collStats scale divides sizes e.g. for KB use 1024 In the shell: > // to see params etc.: > db.foo.stats function (scale) { return this.db.runCommand( ); } // to run: > db.foo.stats ...
Command Line Parameters
MongoDB can be configured via command line parameters in addition to file based configuration. You can see the currently supported set of command line options by running the database with {{\h \ \help \}} as a single parameter: $ ./mongod help Information on usage ...
Commands
Introduction The Mongo database has a concept of a database command. Database commands are ways to ask the database to perform special operations, or to request information about its current operational status. List of Database Commands The MongoDB Manual http://docs.mongodb.org/manual ...
Community
Technical Support See the Support page, free support is available and its usage encouraged! Technical Support Bug/Feature Tracker (Jira) File, track, and vote on bugs and feature requests. http://jira.mongodb.org There is issue tracking for MongoDB and all supported ...
Community Info
Compact Command
v2.0\ The compact command compacts and defragments a collection. Indexes are rebuilt at the same time. It is conceptually similar to {{repairDatabase}}, but works on a single collection rather than an entire database. To run (example from the mongo shell): > db.runCommand( ) OR > db.mycollection.runCommand( "compact" ) The command ...
Comparing Mongo DB and Couch DB
We are getting a lot of questions "how are mongo db and couch different?"&nbsp; It's a good question: both are documentoriented databases with schemaless http://blog.mongodb.org/post/119945109/whyschemaless JSONstyle object data storage.&nbsp; Both products have their place \\ we are big ...
Components
Configuring Sharding
document describes the steps involved in setting up a basic sharding cluster. A sharding cluster has three components: 1. One to 1000 shards. Shards are partitions of data. Each shard consists of one or more {{mongod}} processes which store ...
Connecting
C\ driver includes several classes for managing collections under the parent class DBClientInterface. DBClientConnection is our normal connection class for a connection to a single MongoDB database server (or shard manager). Other classes exist for connecting to a replica set. See ...
Connecting Drivers to Replica Sets
Ideally a MongoDB driver can connect to a cluster of servers which represent a replica set DOCS:Replica Sets, and automatically find the right set member with which to communicate.&nbsp; Failover should be automatic too.&nbsp; The general steps are: # The user ...
Connecting to Replica Sets from Clients
Most drivers have been updated to provide ways to connect to a replica set. In general, this is very similar to how the drivers support connecting to a replica pair. Instead of taking a pair of hostnames, the drivers will typically take a comma separated list of host ...
Connections
MongoDB is a database server: it runs in the foreground or background and waits for connections from the user. Thus, when you start MongoDB, you will see something like: /$ ./mongod # # some logging output # Tue Mar 9 11:15:43 waiting ...
Contributing to the Documentation
Qualified volunteers are welcome to assist in editing the wiki documentation. Contact us for more information
Contributing to the Perl Driver
easiest way to contribute is to file bugs and feature requests on Jira http://jira.mongodb.org/browse/PERL. If you would like to help code the driver, read on... Finding Something to Help With Fixing Bugs You can choose a bug on Jira http ...
Contributors
10gen Contributor Agreement http://www.10gen.com/contributor
Conventions for Mongo Drivers
Interface Conventions It is desirable to keep driver interfaces consistent when possible. Of course, idioms vary by language, and when they do adaptation is appropriate. However, when the idiom is the same, keeping the interfaces consistent across drivers is desirable. Terminology In general, use ...
cookbook.mongodb.org
Copy Database Commands
MongoDB includes commands for copying a database from one server to another. These options are faster than the alternative of doing a mongodump and mongorestore since they skip the step of creating a temporary ondisk BSON representation. copydb Command Copies an entire database ...
createCollection Command
Use the createCollection command Commands to create a collection explicitly. Often this is used to declare capped collections. > // mongo shell > db.createCollection("mycoll", ) // Size is in bytes > show collections Most drivers also have a create collection helper method. You can ...
Creating and Deleting Indexes
CSharp Community Projects
Community Supported C# Drivers See also: the 10gen supported MongoDB C# driver DOCS:CSharp Language Center mongodbcsharp driver http://github.com/samus/mongodbcsharp/tree/master simplemongodb driver http://code.google.com/p/simplemongodb/ NoRM ...
CSharp Driver LINQ Tutorial
Introduction This tutorial covers the support for LINQ queries added in the 1.4 release of the C# driver. You should already have read at least the quickstart introduction to the C# driver. http://www.mongodb.org/display/DOCS/CSharpDriverQuickstart Quickstart First, add the following ...
CSharp Driver Quickstart
Introduction This quickstart provides just enough information to get you started using the C# driver. After you have gotten started you can refer to the rest of the documentation for more information. Downloading the C# driver You can download ...
CSharp Driver Serialization Tutorial
Introduction This document refers to version 1.2 of the C# Driver. This section of the C# Driver Tutorial discusses serialization (and deserialization) of instances of C# classes to and from BSON documents. Serialization is the process of mapping an object to a BSON document that can be saved in MongoDB ...
CSharp Driver Tutorial
C# Driver version v1.4.x This tutorial is for v1.4.x of the C# Driver. Introduction This tutorial introduces the 10gen supported C# Driver for MongoDB. The C# Driver consists of two libraries: the BSON Library and the C# Driver. The BSON Library can be used independently ...
CSharp getLastError and SafeMode
C# driver SafeMode can be set at different levels. 1. At the server level via the connection string: var connectionString = "mongodb://hostname/?safe=true;w=2;wtimeout=30s"; var server = MongoServer.Create(connectionString); 2. At the database level ...
CSharp Language Center
MongoDB C# / .NET Driver The MongoDB C# Driver is the 10gensupported C# / .NET driver for MongoDB. C# Driver QuickStart CSharp Driver QuickStart C# Driver Tutorial CSharp Driver Tutorial C# Driver LINQ Tutorial CSharp Driver ...
Cursors

D

Data Center Awareness
Examples One primary data center, one disaster recovery site Multiple set members can be primary at the main data center. Have a member at a remote site that is never primary (at least, not without human intervention). { id: 'myset', members ...
Data Processing Manual
data processing", we generally mean operations performed on large sets of data, rather than small interactive operations. Import One can always write a program to load data of course, but the mongoimport DOCS:Import Export Tools utility ...
Data Types and Conventions
MongoDB (BSON) Data Types Mongo uses special data types in addition to the basic JSON types of string, integer, boolean, double, null, array, and object. These types include date, object id Object IDs, binary data, regular ...
Database Internals
section provides information for developers who want to write drivers or tools for MongoDB, \ contribute code to the MongoDB codebase itself, and for those who are just curious how it works internally. Subsections of this section
Database Profiler
Mongo includes a profiling tool to analyze the performance of database operations. See also the currentOp DOCS:Viewing and Terminating Current Operation command. Enabling Profiling Through the profile command You can enable and disable profiling from the mongo shell ...
Database References
MongoDB is nonrelational (no joins), references ("foreign keys") between documents are generally resolved clientside by additional queries to the server ("linking"). These links are always resolved clientside. Doing this directly/manually can be quite easy and is recommended. There is also a DBRef mechanism which ...
Databases
Each MongoDB server can support multiple databases. Each database is independent, and the data for each database is stored separately, for security and ease of management. A database consists of one or more collections DOCS:Collections, the documents DOCS:Documents (objects) in those ...
Dates
BSON Date/Time data type is referred to as "UTC DateTime" in the BSON spec http://bsonspec.org. Note There is a Timestamp data type but that is a special internal type for MongoDB that typically should not be used. A BSON Date value stores the number of milliseconds since ...
DBA Operations from the Shell
page lists common DBAclass operations that one might perform from the MongoDB shell DOCS:mongo The Interactive Shell. Note one may also create .js scripts to run in the shell for administrative purposes. help show help show ...
dbshell Reference
Command Line {{\help}} Show command line options {{\nodb}} Start without a db, you can connect later with {{new Mongo()}} or {{connect()}} {{\shell}} After running a .js file from the command line, stay in the shell rather than ...
Demo App in Python
From an Interop 2009 presentation Code: http://github.com/mdirolf/simplemessagingservice/tree/master
Design Overview
Developer FAQ
See also: Intro FAQ FAQ DOCS:Sharding FAQ DOCS:Replica Set FAQ DOCS:Indexing Advice and FAQ Markus Gattol's excellent FAQ on his website http://www.markusgattol.name/ws/mongodb.html What's a "namespace"? MongoDB stores ...
Developer Zone
Tutorial Shell mongo The Interactive Shell Manual Databases Collections Indexes Data Types and Conventions GridFS Inserting Updating Querying Removing Optimization Developer FAQ Cookbook http://cookbook.mongodb.org If you have a comment or question about anything, please ...
Diagnostic Tools
Django and MongoDB
Do I Have to Worry About SQL Injection
See link at bottom for driver specific security notes; specifically one for PHP http://us.php.net/manual/en/mongo.security.php. Instructions for the MongoDB server cluster are represented in two forms: # BSON # Javascript With BSON being the main mechanism. BSON As a client ...
Doc Index
Document-Oriented Datastore
Documentation
Documents
MongoDB can be thought of as a documentoriented database. By 'document', we mean structured documents, not freeform text documents. These documents can be thought of as objects http://blog.10gen.com/post/437029788/jsondbvsodbms but only the data of an object, not the code, methods or class hierarchy. Additionally, there is much ...
Dot Notation
Dot Notation
Dot Notation (Reaching into Objects)
MongoDB is designed for storing JSONstyle objects.&nbsp; The database understands the structure of these objects and can reach into them to evaluate query expressions. Let's suppose we have some objects of the form: > db.persons.findOne() { name: "Joe", address: , likes: 'scuba', 'math ...
dotCloud
Running MongoDB on dotCloud MongoDB can run on dotCloud http://www.dotcloud.com/. It supports replica sets, and has alpha support for sharding. The whole point of dotCloud is to run your apps and your databases in the same place, to optimize for latency and reliability. However ...
Downloads
table id="downloads"> <thead> <tr> <td></td> <td class="tabletop tableleft odd">OS X 32bit<br/><a href="#32bitlimit" class="warning">note</a></td> <td class="tabletop even">OS X 64bit</td ...
Driver and Integration Center
Driver Syntax Table
wiki generally gives examples in JavaScript, so this chart can be used to convert those examples to any language. JavaScript Python PHP Ruby Java C\ C# Perl \ \ \\ {{array()}} \\ {{BasicDBList}} {{BSONObj or bson::bo}} {{BsonArray}} \ \ {} {} {{new stdClass ...
Driver Testing Tools
Object IDs driverOIDTest for testing toString > db.runCommand
Drivers
MongoDB currently has client support for the following programming languages: mongodb.org Supported C C Language Center C\ C Language Center Erlang Erlang Language Center Haskell Haskell Language Center Java Java Language Center ...
Durability and Repair
MongoDB (specifically, the mongod process) is normally ran with journaling enabled. This makes it crashsafe. Journaling is on by default in v2.0 for 64 bit builds. (Use journaling, leave it enabled.) Journaling Enabled If you are running with Journaling you should not do a repair to recover ...
Durability Internals
main durability page (not the internals page) is the Journaling page. Files The data file format is unchanged. Journal files are placed in /data/db/journal/. Running Run with {{journal}} to enable journaling/durable storage. Both {{mongod}} and {{test}} support this option ...

E

EC2 Backup & Restore
Overview This article describes how to backup, verify & restore a MongoDB running on EC2 using EBS Snapshots http://aws.amazon.com/ebs. Backup How you backup MongoDB will depend on whether you are using the journal option in 1.8 (or above) or not. Backup ...
Emacs tips for MongoDB work
You can edit confluence directly from emacs: First, follow the basic instructions on http://code.google.com/p/confluenceel/ Change the confluenceurl in their sample setup to http://mongodb.onconfluence.com/rpc/xmlrpc Might also want to change the default space to DOCS ...
Erlang Language Center
Driver Download https://github.com/mongodb/mongodberlang API Docs http://api.mongodb.org/erlang Design of the Erlang Driver http://blog.mongodb.org/post/7270427645/designoftheerlangdriverformongodb post on blog.mongodb.org Third Party Frameworks and Libs Mongrel http://code.google.com/p/mongrel/ A record/document ...
Error Codes
you have and error event and it isn't obvious what the error is, query for that error code on Jira http://jira.mongodb.org/. If still nothing please post to support forums. This list is HIGHLY incomplete. This page is a stub. Error Code \\ Description \\ Comments \\ 10003 ...
Error Handling in Mongo Drivers
an error occurs on a query (or getMore operation), Mongo returns an error object instead of user data. The error object has a first field guaranteed to have the reserved key {{$err}}. For example: The {{$err}} value can be of any type ...
Events
MongoDB User Groups (MUGs) all over the world. Please check out the full listing http://www.mongodb.org/display/DOCS/MongoDBUserGroups%28MUGs%29. Upcoming Meetups and Conferences Date Event What/Where May 1820, 2012 NoSQL ...
Excessive Disk Space
Understanding Disk Usage You may notice that for a given set of data the MongoDB datafiles in {{/data/db}} are larger than the data set inserted into the database. There are several reasons for this. local.\ files and replication The replication oplog DOCS:Replication Oplog Length ...
Explain
Basics A great way to get more information on the performance of your database queries is to use the {{$explain}} feature. This will display "explain plan" information about a query from the database. When using the mongo shell DOCS:mongo The Interactive Shell, invoke ...

F

FAQ
FAQ answers basic questions for new evaluators of MongoDB. See also: Developer FAQ DOCS:Sharding FAQ DOCS:Replica Set FAQ DOCS:Indexing Advice and FAQ DOCS:Production Notes What kind of database is the Mongo database ...
Feature Checklist for Mongo Drivers
Functionality Checklist This section lists tasks the driver author might handle. Essential BSON serialization/deserialization Basic operations: {{query}}, {{insert}}, {{update}}, {{remove}}, {{ensureIndex}}, {{findOne}}, {{limit}}, {{sort}} Fetch more data from a cursor when necessary ...
File Based Configuration
addition to accepting command line parameters, MongoDB can also be configured using a configuration file. A configuration file can be specified using the {{\f}} or {{\config}} command line options. On some packaged installs of MongoDB (for example Ubuntu & Debian), the default ...
findAndModify Command
Find and Modify (or Remove) v1.3.0 and higher MongoDB 1.3\ supports a "find, modify, and return" command.&nbsp; This command can be used to atomically modify a document (at most one) and return it. Note that, by default, the document returned will not include the modifications made on the update ...
flushRouterConfig command
flushRouterConfig This command will clear the current cluster information that a mongos DOCS:Architecture and Components process has cached and load the latest settings from the config db. This can be used to force an update when the config db and the data cached in mongos ...
Forcing a Member to be Primary
Replica sets automatically negotiate which member of the set is primary and which are secondaries. If you want a certain member to be primary, there are a couple ways to force this. v2.0 In v2.0, you can set the priority of the preferred primary to be higher than the priorities of the other ...
Frequently Asked Questions - Ruby
list of frequently asked questions about using Ruby with MongoDB. If you have a question you'd like to have answered here, please add it in the comments. Can I run \insert command name here\ from the Ruby driver? Yes ...
fsync Command
v1.4 fsync Command The fsync command allows us to flush all pending writes to datafiles.&nbsp; More importantly, it also provides a lock option that makes backups easier. The fsync command forces the database to flush all datafiles: > use ...
Full Text Search in Mongo
Introduction Mongo provides some functionality that is useful for text search and tagging. Multikeys (Indexing Values in an Array) The Mongo multikey feature can automatically index arrays of values. Tagging is a good example of where this feature is useful. Suppose you ...

G

Geospatial Haystack Indexing
addition to ordinary 2d geospatial indices, mongodb supports the use of bucketbased geospatial indexes. Called "Haystack indexing", these indices can accelerate smallregion type longitude / latitude queries when additional criteria is also required. For example, "find all ...
Geospatial Indexing
v1.4\ MongoDB supports twodimensional geospatial indexes. It is designed with locationbased queries in mind, such as "find me the closest N items to my location." It can also efficiently filter on additional criteria, such as "find me the closest N museums to my location ...
getCmdLineOpts command
getCmdLineOpts}} command return both raw and formatted versions of the command line options used to start {{mongod}}. use admin db.runCommand( ) { "argv" : "mongod", "replSet", "replicasetfoo", "logpath", "/data/mongod.log", "oplogSize", "512", "nojournal", "dbpath", "/data/rs30000", "port", "30000 ...
getLastError Command
MongoDB does not wait for a response by default when writing to the database. Use the getLastError command to ensure that operations have succeeded. Many of the drivers can invoke the getLastError command automatically on a write operation. Enabling this driver option is called "safe mode ...
getLastError_old
getLog Command
LogRelated Commands With the {{getLog}} command you can return a list of the log categories available and then all the messages for those categories. This command was introduced in 1.9.2. > db.adminCommand( ) Getting Categories To get all possible log categories, pass {{getLog}} a "" option. > db.adminCommand ...
Getting Started
Getting the Software
Placeholder $$$ TODO
GridFS
GridFS is a specification for storing large files in MongoDB. All of the mongodb.org supported drivers implement the GridFS spec DOCS:GridFS Specification. Rationale The database supports native storage of binary data within BSON DOCS:BSON objects.&nbsp; However ...
GridFS in Ruby
GridFS, which stands for "Grid File Store," is a specification for storing large files in MongoDB. It works by dividing a file into manageable chunks and storing each of those chunks as a separate document. GridFS requires two collections to achieve this: one collection stores ...
GridFS Specification
Introduction GridFS is a storage specification for large objects in MongoDB. It works by splitting large object into small chunks, usually 256k in size. Each chunk is stored as a separate document in a {{chunks}} collection. Metadata about the file, including the filename, content type ...
GridFS Tools
File Tools {{mongofiles}} is a tool for manipulating GridFS DOCS:Storing Files from the command line. Example: $ ./mongofiles list connected to: 127.0.0.1 $ ./mongofiles put libmongoclient.a connected to: 127.0.0.1 done! $ ./mongofiles list connected to: 127.0.0.1 libmongoclient.a 12000964 $ cd ...

H

Hadoop
MongoDB Hadoop Adapter is a plugin for Hadoop that provides Hadoop the ability to use MongoDB as an input source and/or an output source. The source code is available on github https://github.com/mongodb/mongohadoop where you can find a more comprehensive ...
Halted Replication
instructions are for master/slave replication. For replica sets, see DOCS:Resyncing a Very Stale Replica Set Member instead. If you're running mongod with masterslave replication DOCS:Master Slave, there are certain scenarios where the slave will halt replication because ...
Haskell Language Center
Haskell driver and its API documentation reside on Hackage http://hackage.haskell.org/package/mongoDB
Home
MongoDB Manual http://docs.mongodb.org/manual/ is a complete rewrite of the MongoDB documentation that will eventually replace this site. You can view the latest build at docs.mongodb.org http://docs.mongodb.org, and contribute on github http://github.com/mongodb/docs and Jira http://jira.mongodb.org/browse ...
Hosting Center
DatabaseasaService MongoOd.com http://mongood.com/ MongoLab https://mongolab.com/home/ HostedMongo.com http://hostedmongo.com/ MongoGrid http://nodegrid.com/resources/mongogrid/ InfrastructureasaService Amazon EC2 DOCS:Amazon EC2 Joyent DOCS:Joyent PlatformasaService alwaysdata http://blog.alwaysdata.com/en/2011/04/26/officialsupportofmongodb ...
How does concurrency work
Latest info in this video : http://www.10gen.com/presentations/concurrencyinternalsmongodb22 The documentation below covers for MongoDB v2.0. v2.0 typically achieves significantly more concurrency in disk activity than v1.8 did. v2.2 will include substantial enhancements with concurrency work being by far ...
How MongoDB is Used in Media and Publishing
We see growing usage of MongoDB in both traditional and new media organizations. In these areas, the challenges for application developers include effectively managing rich content (including usergenerated content) at scale, deriving insight into how content is consumed and shared in realtime ...
How to do Snapshotted Queries in the Mongo Database
document refers to query snapshots. For backup snapshots of the database's datafiles, see the fsync lock page fsync Command. MongoDB does not support full pointintime snapshotting. However, some functionality is available which is detailed below. Cursors A MongoDB query ...
How to Make an Auto Incrementing Field
Generally in MongoDB, one does not use an autoincrement pattern for \id's (or other fields), as this does not scale up well on large database clusters. Instead one typically uses Object IDs. Side counter method One can keep ...
HowTo
Http Interface
REST Interfaces Sleepy Mongoose (Python) Sleepy Mongoose http://www.snailinaturtleneck.com/blog/2010/02/22/sleepymongooseamongodbrestinterface/ is a full featured REST interface for MongoDB which is available as a separate project. MongoDB Rest (Node.js) MongoDB Rest http://github.com/tdegrunt/mongodbrest is an alpha ...

I

Implementing Authentication in a Driver
current version of Mongo supports only very basic authentication.&nbsp; One authenticates a username and password in the context of a particular database.&nbsp; Once authenticated, the user has full read and write access to the database in question. The {{admin}} database is special ...
Import Export Tools
you just want to copy a database from one mongod server to another, use the copydb Command Copy Database Commands instead of these tools. These tools work with the raw data (the BSON documents in the collections, both user and system); they do not save ...
Index Versions
MongoDB v2.0 uses a new data structure for its indexes. The new {{\{v:1\}}} indexes are, on average, 25% smaller than the old {{\{v:0\}}} indexes. This usually results in significantly increased performance. In addition, signed (pre 1970) dates ...
Index-Related Commands
Operations: Create Index {{ensureIndex()}} is the helper function for this. Its implementation creates an index by adding its info to the {{system.indexes}} collection. > use test > db.myCollection.ensureIndex(<keypattern>); > // same as: > db.system.indexes.insert( ); Note: Once you've inserted the index, all subsequent document ...
Indexes
Indexes enhance query performance, often dramatically. It's important to think about the kinds of queries your application will need so that you can define relevant indexes. Once that's done, actually creating the indexes in MongoDB is relatively easy. Indexes in MongoDB ...
Indexes in Mongo
Indexing Advice and FAQ
We get a lot of questions about indexing. Here we provide answers to a number of these. There are a couple of points to keep in mind, though. First, indexes in MongoDB work quite similarly to indexes in MySQL, and thus many of the techniques for building efficient indexes ...
Indexing as a Background Operation
Prior to 2.1.0, slaves and replica secondaries build indexes in the foreground even if {{background:true}} is specified. The slave/secondary will block queries while the index builds on it. Indexing on the secondaries begins after the index is completely built on the primary. {}v1.4\ By default the {{ensureIndex ...
Inserting
When we insert data into MongoDB, that data will always be in documentform. Documents are data structure analogous to JSON, Python dictionaries, and Ruby hashes, to take just a few examples. Here, we discuss more about documentorientation and describe how to insert ...
Installing the PHP Driver
Internal Commands
Most commands Commands have helper functions and do not require the {{$cmd.findOne()}} syntax. These are primarily internal and administrative. > db.$cmd.findOne( ) > db.$cmd.findOne( ) { "uptime" : 6 , "globalLock" : , "mem" : , "ok" : 1 } > admindb.$cmd.findOne( ) // close all databases. a subsequent request ...
Internals
Cursors Tailable Cursors See p/db/dbclient.h for example of how, on the client side, to support tailable cursors. Set OptionCursorTailable = 2 in the {{queryOptions int}} field to indicate you want a tailable cursor. If you get back no results when ...
International Docs
Most documentation for MongoDB is currently written in English. We are looking for volunteers to contribute documentation in other languages. If you're interested in contributing to documentation in another language please email docs at 10gen dot com. Language Homepages !de.png! Deutsch DOCSDE ...
International Documentation
Internationalized Strings
MongoDB supports UTF8 for strings in stored objects and queries.&nbsp; (Specifically, BSON DOCS:BSON strings are UTF8.) Generally, drivers for each programming language convert from the language's string format of choice to UTF8 when serializing and deserializing BSON ...
Introduction
MongoDB wasn’t designed in a lab. We built MongoDB from our own experiences building large scale, high availability, robust systems. We didn’t start from scratch, we really tried to figure out what was broken ...
Introduction - How Mongo Works
iostat
Linux, use the iostat command to check if disk I/O is a bottleneck for your database. We generally find the form: iostat xm 2 to work well. (Use a number of seconds with iostat, otherwise it will display stats since server boot ...

J

Java - Saving Objects Using DBObject
Java driver provides a DBObject interface to save custom objects to the database. For example, suppose one had a class called Tweet that they wanted to save: public class Tweet implements DBObject Then you can say: Tweet myTweet = new Tweet ...
Java Driver Concurrency
Java MongoDB driver is thread safe. If you are using in a web serving environment, for example, you should create a single Mongo instance, and you can use it in every request. The Mongo object maintains an internal pool of connections to the database ...
Java Language Center
Java Driver Basics Download the Java Driver http://github.com/mongodb/mongojavadriver/downloads Tutorial http://www.mongodb.org/display/DOCS/JavaTutorial API Documentation http://api.mongodb.org/java/index.html Release Notes https://github.com/mongodb/mongojavadriver/wiki ...
Java Tutorial
Introduction This page is a brief overview of working with the MongoDB Java Driver. For more information about the Java API, please refer to the online API Documentation for Java Driver http://api.mongodb.org/java/index.html A Quick Tour Using the Java driver is very ...
Java Types
Object Ids {{com.mongodb.ObjectId}} http://api.mongodb.org/java/0.11/com/mongodb/ObjectId.html is used to autogenerate unique ids. ObjectId id = new ObjectId(); ObjectId copy = new ObjectId(id); Regular Expressions The Java driver uses {{java.util.regex.Pattern}} http://java.sun.com ...
Javascript Language Center
MongoDB can be Used by clients written in Javascript; Uses Javascript internally serverside for certain options such as map/reduce; Has a shell DOCS:mongo The Interactive Shell that is based on Javascript for administrative purposes. node.JS and V8 See the node.JS page. node.JS ...
Job Board
Redirecting
Journaling
MongoDB v1.7.5 supports writeahead journaling of operations to facilitate fast crash recovery and durability in the storage engine. Disabling/Enabling In version 1.9.2, journaling is enabled by default for 64bit platforms. You can disable journaling with the mongod {{\\nojournal}} command line ...
Journaling Administration Notes
Journal Files (e.g. journal/j.0) Journal files are appendonly and are written to the {{journal/}} directory under the dbpath directory (which is {{/data/db/}} by default). Journal files are named {{j.0}}, {{j.1}}, etc. When a journal file reached 1GB in size ...
Joyent
quickest start, you can use the Joyent SmartMachine for MongoDB Appliance http://wiki.joyent.com/display/jpc2/JoyentMongoDBSmartMachine For installing MongoDB on a Joyent Node Smart Machine, see this article http://wiki.joyent.com/display/node/InstallingMongoDBonaNodeSmartMachine The prebuilt DOCS:Downloads MongoDB Solaris ...
JS Benchmarking Harness
benchRun command is designed as a QA baseline perf measurement tool, not designed to be a "benchmark". CODE: db.foo.drop(); db.foo.insert( ) ops = { op : "findOne" , ns : "test.foo" , query : } , { op : "update" , ns : "test.foo" , query : , update : { $inc : } } for ( x = 1; x<=128 ...
JVM Languages

K

Kernel class rules
Design guidelines {}Never use multiple inheritance{}. If you need the service of several classes, use delegation. The only possible but highly unlikely exception to this is if your class inherits from other pure abstract classes. Have a comment before a class ...
Kernel code style
basics Use spaces, no literal tabs. 4 spaces per indentation. Limit lines to 100 columns. case Use camelCase for most {{varNames}} See important notes on case on the parent page for user facing names\! comments We follow ...
Kernel concurrency rules
All concurrency classes must be placed under {{utils/concurrency}}. You will find several helper libraries there. Do not add mutexes without discussion with others. Concurrency and correctness is very hard in the large. Great care is required. For example the concurrency model ...
Kernel exception architecture
several different types of assertions used in the MongoDB code. In brief: {{uassert}} checks for peroperation user errors. Operationfatal. {{massert}} checks peroperation invariants. Operationfatal. {{verify}} is a synonym for massert, that doesn't require an error code. {{fassert}} checks fatal ...
Kernel logging
Basic Rules cout/cerr should never be used Normal Logging debugging with levels of verbosity. default=0 (use just log() for that). See v command line option. LOG( int x ) << ... informational log() << ... rate limited LOGSOME ...
Kernel string manipulation
string manipulation, use the {{util/mongoutils/str.h}} library. {{str.h}} {{util/mongoutils/str.h}} provides string helper functions for each manipulation. Add new functions here rather than lines and lines of code to your app that are not generic. Typically ...

L

Language Support
Legal Key Names
Key names in inserted documents are limited as follows: The '$' character must not be the first character in the key name. The '.' character must not appear anywhere in the key name
Licensing
Database: Free Software Foundation's GNU AGPL v3.0 http://www.fsf.org/licensing/licenses/agpl3.0.html. Commercial licenses are also available from 10gen mailto:info@10gen.com, including free evaluation licenses. Drivers: mongodb.org supported drivers: Apache License ...
List of Database Commands
iframe src ="http://api.mongodb.org/internal/current/commands.html" width="100%" height="1000px" frameborder="0"> <a href="http://api.mongodb.org/internal/current/commands.html">List of MongoDB Commands</a> </iframe> See the Commands page for details on how to invoke a command ...
List of helper functions
nonexhaustive list of helper functions for use in the C stream syntax. An exhaustive list is here: bsonmisc.h https://github.com/mongodb/mongo/blob/master/src/mongo/bson/bsonmisc.h Typical example of stream syntax: BSONObj p = BSON ...
Locking
Locking in Mongo
Logging
MongoDB outputs some important information to stdout while its running. There are a number of things you can do to control this Command Line Options {{\quiet}} less verbose output (more details quiet) {{v}} more verbose output. use ...

M

Manual
MongoDB manual.&nbsp; Except where otherwise noted, all examples are in JavaScript for use with the mongo shell mongo The Interactive Shell.&nbsp; There is a table Driver Syntax Table available giving the equivalent syntax for each of the drivers
MapReduce
Map/reduce in MongoDB is useful for batch processing of data and aggregation operations. It is similar in spirit to using something like Hadoop with all input coming from a collection and output going to a collection. Often, in a situation where you would have used ...
Master Slave
Use Replica Sets DOCS:Replica Sets rather than this – replica sets are a functional superset of master/slave, and newer, more robust code. Configuration and Setup To configure an instance of Mongo to be a master database in a masterslave configuration, you'll need ...
Memory management
Overall guidelines avoid using bare pointers for dynamically allocated objects. Prefer scopedptr, sharedptr, or another RAII class such as BSONObj. do not use autoptr's and refactor legacy ones out whenever possible. (Careful with c driver and backward compatibility ...
min and max Query Specifiers
min()}} and {{max()}} functions may be used in conjunction with an index to constrain query matches to those having index keys between the min and max keys specified. The {{min()}} and {{max()}} functions may be used individually or in conjunction. The index to be used may ...
Misc
mongo - The Interactive Shell
MongoDB distribution Downloads includes {{bin/mongo}}, the MongoDB interactive shell. This utility is a JavaScript shell that allows you to issue commands to MongoDB from the command line. (it is basically an extended SpiderMonkey https://developer.mozilla.org/En/SpiderMonkey/IntroductiontotheJavaScriptshell shell ...
Mongo Administration Guide
Mongo Concepts and Terminology
See the Manual page Manual for information on the following: BSON Collections Cursors Databases Documents GridFS (for files and very large objects) Indexes Transactions / Atomic Operations Other Concepts Config server. In a sharded environment Sharding Introduction#ArchitecturalOverview, config ...
Mongo Database Administration
Mongo Developers' Guide
Mongo Documentation Style Guide
page provides information for everyone adding to the Mongo documentation on Confluence. It covers: #General Notes on Writing Style Guide to Confluence markup for specific situations Some general notes about doc production General Notes on Writing Style Voice Active ...
Mongo Driver Requirements
highlevel list of features that a driver for MongoDB might provide. We attempt to group those features by priority. This list should be taken with a grain of salt, and probably used more for inspiration than as law that must be adhered to. A great way to learn about ...
Mongo Extended JSON
Mongo's REST interface supports storage and retrieval of JSON documents. Special representations are used for BSON types that do not have obvious JSON mappings, and multiple representations are allowed for some such types. The REST interface supports three different modes for document ...
Mongo Metadata
dbname>.system.}} namespaces in MongoDB are special and contain database system information.&nbsp; System collections include: {{<dbname>.system.namespaces}} lists all namespaces. {{<dbname>.system.indexes}} lists all indexes. Additional namespace / index metadata exists in the database.ns files ...
Mongo Query Language
Queries in MongoDB are expressed as JSON (BSON). Usually we think of query object as the equivalent of a SQL "WHERE" clause: > db.users.find( ).sort( ); // select from users where x=3 and y='abc' order by x asc; However, the MongoDB server ...
Mongo Usage Basics
Mongo Wire Protocol
Introduction The Mongo Wire Protocol is a simple socketbased, requestresponse style protocol. Clients communicate with the database server through a regular TCP/IP socket. The default port is 27017, but this is configurable and will vary. Clients should connect to the database with a regular TCP/IP ...
Mongo-Based Applications
Please list applications that leverage MongoDB here. If you're using MongoDB for your application, we'd love to list you here\!&nbsp; Email meghan@10gen.com. See Also Production Deployments Companies and Sites using MongoDB Hosting Center Applications ...
MongoDB - A Developer's Tour
MongoDB Commercial Services Providers
10gen.png! http://www.10gen.com/ is the initiator, contributor and continual sponsor of the MongoDB project. 10gen offers subscriptions that include production support http://www.10gen.com/support, commercial licensing http://www.10gen.com/commerciallicenses, and MongoDB Monitoring Service http://www.10gen.com/mongodbmonitoringservice. In addition ...
MongoDB Data Modeling and Rails
tutorial discusses the development of a web application on Rails and MongoDB.&nbsp; MongoMapper will serve as our object mapper.&nbsp; The goal is to provide some insight into the design choices required for building on MongoDB.&nbsp; To that end, we'll be constructing a simple but nontrivial social ...
MongoDB kernel code development rules
Coding conventions for the MongoDB C code... For anything not mentioned here, default to google c style guide http://googlestyleguide.googlecode.com/svn/trunk/cppguide.xml Git Committing and Pushing commit messages should have the case in the message SERVERXXX commit messages ...
MongoDB Language Support
MongoDB Masters
sorted alphabetically by last name) Rick Copeland Rick Copeland is a Lead Software Engineer at SourceForge where he joined the team that introduced MongoDB to the SourceForge technology stack with the migration of the consumerfacing pages of SourceForge from a PHP/relational database platform ...
MongoDB Monitoring Service
MongoDB Monitoring Service is a free SaaS solution for proactive monitoring of your MongoDB cluster(s). MMS’s web interface features charts, custom dashboards, and automated alerting; and since it runs in the cloud, MMS requires minimal setup and configuration. Within minutes ...
MongoDB on Azure
MongoDB Replica Set Azure wrapper is currently a preview release. Please provide feedback, mongodbdev http://groups.google.com/group/mongodbdev, mongodbuser http://groups.google.com/group/mongodbuser and IRC #mongodb are good places\! The MongoDB Wrapper for Azure allows you ...
MongoDB User Groups (MUGs)
MongoDB User Groups (MUGs) are a great way for the community to learn from one another about MongoDB best practices, to network, and to have fun. Interested in starting a user group in your city? Submit a proposal http://www.10gen.com/usergroups and check ...
MongoDB, CouchDB, MySQL Compare Grid
pending... CouchDB \\ MongoDB \\ MySQL \\ Data Model \\ DocumentOriented (JSON http://www.json.org/) \\ DocumentOriented (BSON http://blog.mongodb.org/post/114440717/bson) \\ Relational \\ Data Types \\ string,number,boolean,array,object string, int, double, boolean, date, bytearray, object ...
mongoexport
mongoexport utility is a command line tool that takes a collection and exports to either JSON or CSV. You can specify a filter for the query, or a list of fields to output. Neither JSON nor TSV/CSV can represent all data types. Please ...
mongoperf
mongoperf is a utility for checking disk i/o performance of a server independent of MongoDB. It performs simple timed random disk i/o's. The utility is new and will likely be more sophisticated in the future. # get help: mongoperf h # example invocation: echo ...
mongosniff
Unix releases of MongoDB include a utility called mongosniff. This utility is to MongoDB what tcpdump is to TCP/IP; that is, fairly low level and for complex situations. The tool is quite useful for authors of driver tools. $ ./mongosniff help Usage: mongosniff help forward ...
mongostat
Use the mongostat utility to quickly view statistics on a running mongod instance. !mongostat.png align=center! Run mongostat help for help. Fields: insert # of inserts per second ( means replicated op) query # of queries per second update # of updates ...
Monitoring
Monitoring and Diagnostics
Admin UIs mongostat mongostat is a great utility which exposes many internal MongoDB metrics. For any MongoDB related issues it is a good start for the analysis of performance issues. mongotop http://docs.mongodb.org/manual/reference/mongotop/ Query Profiler Use ...
movePrimary Command
movePrimary This command allows changing the primary shard for sharded database. The primary will hold all unsharded collections in that database. This command is only available on a sharded system through "mongos". When using this with existing data with sharded collections you must be very ...
Moving Chunks
any given time, a chunk is hosted at one mongod server. The sharding machinery routes all the requests to that server automatically, without the application needing to know which server that is. From times to time, the balancer http://www.mongodb.org/display/DOCS/ShardingAdministration ...
Moving or Replacing a Member
shell you can use the rs.remove() helper to remove a node from a replica set. Then use rs.add() to add the new member to the set. See rs.help() in the shell for more information. See the DOCS:Adding a New Set Member for details on how ...
Multikeys
MongoDB provides an interesting "multikey" feature that can automatically index arrays of an object's values. A good example is tagging. Suppose you have an article tagged with some category names: $ dbshell > db.articles.save( ) > db.articles.find() We can ...
Munin configuration examples
Overview Munin http://muninmonitoring.org can use be used for monitoring aspects of a running system. The following is a mini tutorial to help you set up and use the MongoDB plugin with munin. Setup Munin is made up of two components agent and plugins ...

N

NFS
We have found that some versions of NFS perform very poorly, or simply don't work, and do not suggest using NFS. (We'd love to hear from you if you are using NFS and what results you are getting, either great ...
node.JS
Node.js is used to write eventdriven, scalable network programs in serverside JavaScript. It is similar in purpose to Twisted, EventMachine, etc. It runs on Google's V8. This is an overview of the available tools and suggested practices for using Node.js with MongoDB. Those wishing to skip to more ...
Notes on Pooling for Mongo Drivers
Note that with the db write operations can be sent asynchronously or synchronously (the latter indicating a getlasterror request after the write). When asynchronous, one must be careful to continue using the same connection (socket). This ensures that the next operation will not begin until after ...
NUMA
Linux, NUMA http://en.wikipedia.org/wiki/NonUniformMemoryAccess and MongoDB tend not to work well together. If you are running MongoDB on numa hardware, we recommend turning it off (running with an interleave memory policy). Problems will manifest in strange ways, such as massive ...

O

Object IDs
Documents in MongoDB required a key, {{\id}}, which uniquely identifies them. The \id Field Almost every MongoDB document has an \id field as its first attribute (there are a few exceptions for system collections and capped collections).&nbsp; The id ...
ObjectId
Old Pages
Older Downloads
Online API Documentation
MongoDB API and driver documentation is available online. It is updated daily. Java Driver API Documentation http://api.mongodb.org/java C Driver API Documentation http://api.mongodb.org/cplusplus Python Driver API Documentation http://api.mongodb.org/python Ruby ...
OpenShift Quickstart
OpenShift is a Platform as a Service (PaaS) offering from RedHat, which provides support for rapid deployment and automatic scalability support for web applications developed with Java EE, Node.js, Python, PHP, Perl and Ruby. OpenShift Express is a free sharedcloud solution ...
Optimization
Additional Articles DOCS:Optimizing Object IDs DOCS:Optimizing Storage of Small Objects Optimizing A Simple Example This section describes proper techniques for optimizing database performance. Let's consider an example. Suppose our task is to display the front ...
Optimizing Mongo Performance
Optimizing Object IDs
id}} field in a MongoDB document is very important and is always indexed for normal collections. This page lists some recommendations. Note that it is common to use the BSON ObjectID datatype for id's, but the values of an {{id}} field can be of any type. Use the collections ...
Optimizing Storage of Small Objects
MongoDB records have a certain amount of overhead per object (BSON DOCS:BSON document) in a collection.&nbsp; This overhead is normally insignificant, but if your objects are tiny (just a few bytes, maybe one or two fields) it would not be.&nbsp; Below ...
OR operations in query expressions
Query objects in Mongo by default AND expressions together. $in The $in operator indicates a "where value in ..." expression.&nbsp; For expressions of the form x == a OR x == b, this can be represented as { x : } $or v1.5.3 The {{$or}} operator lets you use a boolean or expression to do queries. You ...
Overview - The MongoDB Interactive Shell
Running the Shell The interactive shell is included in the standard MongoDB distribution. To start the shell, go into the root directory of the distribution and type ./bin/mongo It might be useful to add {{{}mongodistributionroot/bin}} to your {{PATH}} so you can just type {{mongo ...
Overview - Writing Drivers and Tools
section contains information for developers that are working with the lowlevel protocols of Mongo people who are writing drivers and higherlevel tools. Documents of particular interest : BSON http://bsonspec.org Description of the BSON binary document format. Fundamental to how Mongo and it's client software ...

P

Padding Factor
Overview When you update a document in MongoDB, the update occurs inplace if the document has not grown in size. If the document did grow in size, however, then it might need to be relocated on disk to find a new disk location with enough contiguous space to fit ...
Pairing Internals
Policy for reconciling divergent oplogs pairing is deprecated In a paired environment, a situation may arise in which each member of a pair has logged operations as master that have not been applied to the other server. In such a situation, the following procedure will be used to ensure consistency ...
Parsing Stack Traces
addr2line addr2line e mongod ifC <offset> cfilt You can use {{cfilt}} to demangle function names by pasting the whole stack trace to stdin. Finding the right binary To find the binary you need: Get the commit at the header of any ...
Perl Language Center
Installing Start a MongoDB server instance ({{mongod}}) before installing so that the tests will pass. The {{mongod}} cannot be running as a slave for the tests to pass. Some tests may be skipped, depending on the version of the database you are running. CPAN $ sudo cpan MongoDB ...
Perl Tutorial
Philosophy
Design Philosophy !featuresPerformace.png align=right! New database technologies are needed to facilitate horizontal scaling of the data layer, easier development, and the ability to store order(s) of magnitude more data than was used in the past. A nonrelational approach is the best path to database ...
PHP - Storing Files and Big Data
PHP Language Center
Using MongoDB in PHP To access MongoDB from PHP you will need: The MongoDB server running the server is the "mongo{}d" file, not the "mongo" client (note the "d" at the end) The MongoDB PHP driver installed Installing the PHP Driver \NIX Run ...
PHP Libraries, Frameworks, and Tools
PHP community has created a huge number of libraries to make working with MongoDB easier and integrate it with existing frameworks. Libraries and Frameworks CakePHP MongoDB datasource https://github.com/ichikaway/cakephpmongodb for CakePHP. There's also an introductory blog post http ...
Production Deployments
you're using MongoDB in production, we'd love to list you here\!&nbsp; Please complete this web form https://www.10gen.com/weusemongodb and we will add you. Archiving <DIV mcestyle="textalign:center;margin:0" style="margin: 0pt ...
Production Notes
Backups Backups Doc Page DOCS:Backups Import Export Tools TCP Port Numbers Default TCP port numbers for MongoDB processes: Standalone {{mongod}} : 27017 {{mongos}} : 27017 shard server DOCS:Architecture and Components ({{mongod \shardsvr ...
Project Ideas
you're interested in getting involved in the MongoDB community (or the open source community in general) a great way to do so is by starting or contributing to a MongoDB related project. Here we've listed some project ideas for you to get started on. For some of these ideas ...
PyMongo and mod_wsgi
Python Language Center
an overview of the available tools for using Python with MongoDB. Those wishing to skip to more detailed discussion should check out the Python Driver Tutorial http://api.mongodb.org/python/current/tutorial.html. Python Driver PyMongo is the recommended way to work ...
Python Tutorial

Q

Queries and Cursors
Queries to MongoDB return a cursor, which can be iterated to retrieve results. The exact way to query will vary with language driver. Details below focus on queries from the MongoDB shell DOCS:mongo The Interactive Shell (i.e. the {{mongo}} process). The shell ...
Query Optimizer
MongoDB query optimizer generates query plans for each query and then executes the plan to return results. Thus, MongoDB supports ad hoc queries much like say, Oracle or MySQL. The database uses an interesting approach to query optimization ...
Querying
One of MongoDB's best capabilities is its support for dynamic (ad hoc) queries. Systems that support dynamic queries don't require any special indexing to find data; users can find data using any criteria. For relational databases ...
Querying and nulls
null}} value in javascript carries different meanings. When a query involves {{null}}, this can have multiple interpretations. Take the following examples: > db.foo.insert( ) > db.foo.insert( ) > db.foo.insert( ) > db.foo.insert( ) // Query #1 > db.foo.find( ) // Query #2 > db.foo.find( { "y" : } ) // Query #3 ...
Quickstart
Quickstart OS X Quickstart Unix Quickstart Windows For an even quicker start go to http://try.mongodb.org/. Installation Guides Consider the installation guides from the MongoDB Manual installation guides from the MongoDB Manual: Install MongoDB on RedHat ...
Quickstart OS X
Install MongoDB The easiest way to install MongoDB is to use a package manager or the prebuilt binaries, described below and on the MongoDB Manual's OS X Installation Guide http://docs.mongodb.org/master/tutorial/installmongodbonosx/. Consider all of the available installation guides http ...
Quickstart Unix
Consider one of the following installation tutorials from the new Manual http://docs.mongodb.org/ for more specific instructions for getting started with MongoDB. Install MongoDB on RedHat Enterprise Linux, CentOS, or Fedora Linux http://docs.mongodb.org/master/tutorial/installmongodbonredhatcentosorfedoralinux/ Install ...
Quickstart Windows
Download The easiest (and recommended) way to install MongoDB is to use the prebuilt binaries. Note: 64bit is recommended http://blog.mongodb.org/post/137788967/32bitlimitations, although you must have a 64bit version of Windows to run that version. 32bit binaries Download Downloads and extract the 32bit ...

R

Rails - Getting Started
Using Rails 3? See Rails 3 Getting Started This tutorial describes how to set up a simple Rails application with MongoDB, using MongoMapper as an object mapper. We assume you're using Rails versions prior to 3.0 ...
Rails 3 - Getting Started
difficult to use MongoDB with Rails 3. Most of it comes down to making sure that you're not loading ActiveRecord and understanding how to use Bundler http://github.com/carlhuda/bundler/blob/master/README.markdown, the new Ruby dependency manager. Install the Rails ...
Recommended Configurations
Replica sets support quite a few options, and it can be confusing determining the best configuration. Here following a few suggestions. One data center If you have just one data center, then the most economical setup is a threenode replica set ...
Recommended Production Architectures
Reconfiguring a replica set when members are down
One can easily reconfigure a replica set when some members are down as long as a majority is still up. In that case, simply send the reconfig command to the current primary. DOCS:Reconfiguring when Members are Up If there is no majority (i.e. a majority of nodes ...
Reconfiguring when Members are Up
v1.8 Use the rs.reconfig() helper in the shell. (Run "rs.reconfig" in the shell with no parenthesis to see what it does.) $ mongo > // example : give 1st member priority 2 > cfg = rs.conf() > cfg.members0.priority = 2 > rs.reconfig(cfg) Earlier versions (1.6) You can ...
RedHat OpenShift
OpenShift https://openshift.redhat.com/app/ is a Platform as a Service (PaaS) offering from RedHat, which provides support for rapid deployment and automatic scalability support for web applications developed with Java EE, Node.js, Python, PHP, Perl and Ruby, and several databases ...
removeshard command
Removing a Shard The {{removeshard}} command will remove a shard from an existing cluster. It has two phases which are described below. Starting Before a shard can be removed, we have to make sure that all the chunks and databases that once lived ...
Removing
Removing Objects from a Collection To remove objects from a collection, use the {{remove()}} function in the mongo shell mongo The Interactive Shell. (Other drivers offer a similar function, but may call the function "delete". Please check your driver's documentation ...
renameCollection Command
renameCollection command cannot be used with sharded collections. This command can be used to rename an existing collection. Shell: > db.oldname.renameCollection("newname") From drivers without a helper method one can invoke the generic command syntax: > db.runCommand( This command is executed ...
Replica Pairs
Replica pairs should be migrated to their replacement, Replica Sets. Setup of Replica Pairs Mongo supports a concept of replica pairs. These databases automatically coordinate which is the master and which is the slave at a given point in time. At startup, the databases will negotiate which is master ...
Replica Set Admin UI
mongod}} process includes a simple administrative UI for checking the status of a replica set. To use, first enable {{\rest}} from the {{mongod}} command line. The rest port is the db port plus 1000 (thus, the default is 28017). Be sure this port is secure ...
Replica Set Authentication
Authentication was added in 1.7.5 Replica set authentication works a little differently from singleserver authentication, so that each member can automatically authenticate itself to the other members of the set. See the main docs on authentication Security and Authentication#Replica Set ...
Replica Set Commands
Shell Helpers rs.help() show help rs.status() rs.initiate() initiate with default settings rs.initiate(cfg) rs.add(hostportstr) add a new member to the set rs.add(membercfgobj) add a new member to the set rs.addArb(hostportstr) add a new member which ...
Replica Set Configuration
Command Line Each {{mongod}} participating in the set should have a {{\replSet}} parameter on its command line. The syntax is mongod replSet setname rest {}setname is the logical name of the set. Use the {{rest}} command line parameter when using replica ...
Replica Set Design Concepts
replica set has at most one primary at a given time. If a majority of the set is up, the most uptodate secondary will be elected primary. If a majority of the set is not up or reachable, no member will be elected primary. There is no way to tell (from the set's point of view) the difference ...
Replica Set FAQ
See Also: Intro FAQ FAQ DOCS:Developer FAQ DOCS:Sharding FAQ How long does replica set failover take? It may take 1030 seconds for the primary to be declared down by the other members and a new primary elected ...
Replica Set Internals
page contains notes on the original MongoDB replica set design. While the concepts still apply, this page is not kept perfectly uptodate; consider this page historical rather than definitive. Design Concepts Check out the Replica Set Design Concepts ...
Replica Set Semantics
MongoDB Java driver handles failover in replicated setups with tunable levels of transparency to the user.&nbsp; By default, a {{Mongo}} connection object will ignore failures of secondaries, and only reads will throw {{MongoExceptions}} when the primary node is unreachable. The level of exception reporting ...
Replica Set Tutorial
v1.6 This tutorial will guide you through a basic replica set initial setup. Given the tutorial is an example and should be easy to try, it runs several mongod processes on a single machine (in the real world one would use several machines ...
Replica Set Versions and Compatibility
Features Feature Version Slave delay v1.6.3 Hidden v1.7 replSetFreeze and replSetStepDown v1.7.3 Replicated ops in {{mongostat}} v1.7.3 Syncing from secondaries v1.8.0 Authentication v1.8.0 Replication from nearest server (by ping time) v2.0.0 Syncing 1.8.x ...
Replica Sets
Overview Replica sets are a form of asynchronous master/slave replication DOCS:Master Slave, adding automatic failover and automatic recovery of member nodes. A replica set consists of two or more nodes that are copies of each other. (i.e.: replicas) The replica ...
Replica Sets - Basics
production use you will want a minimum of three nodes in the replica set. Either: 2 full nodes and 1 arbiter 3 full nodes To avoid a single point of failure, these nodes must be on different computers. It is standard to have at least 2 ...
Replica Sets - Oplog
Replication of data between nodes is done using a special collection known as the {{oplog}}. See also : DOCS:Replication Oplog Length. The basic replication process # All write operations are sent to the server (Insert, Update, Remove, DB/Collection/Index ...
Replica Sets - Priority
default, all full nodes in a replica set have equal priority. If a primary steps down, all other members are electable as the new primary. That is, each node by default has {{priority:1}}. Arbiters DOCS:Adding an Arbiter have ...
Replica Sets - Rollbacks
Overview The classic example of a rollback occurs when you have two replicas (a primaryA and secondaryB) and the secondary (B) is not up to date (replication is behind). If the primary (A) fails (or is shutdown) before B is uptodate and B becomes primary, then there is data which B ...
Replica Sets - Voting
Each replica sets contains only one primary node. This is the only node in the set that can accept write commands (insert/update/delete). The primary node is elected by a consensus vote of all reachable nodes. Consensus Vote For a node to be elected ...
Replica Sets in Ruby
Here follow a few considerations for those using the Ruby driver Ruby Tutorial with MongoDB and replica sets DOCS:Replica Sets. Setup First, make sure that you've configured and initialized a replica set. Connecting to a replica set from the Ruby ...
Replica Sets Limits
set can contain A maximum of 12 members A maximum of 7 members that can vote Typically the set configuration can be changed only when a majority can be established. Limits on config changes to sets at first. Especially when a lot of set ...
Replica Sets slaveDelay
Overview A replica set member can be configured with a {{slaveDelay:<secs>}} option. When {{slaveDelay}} is specified, the member will intentionally remain behind current in its application of replicated writes. This is typically used to keep a "rolling backup" that is a certain amount of time in the past ...
Replica Sets Troubleshooting
can't get local.system.replset config from self or any seed (EMPTYCONFIG) Set needs to be initiated. Run {{rs.initiate()}} from the shell. If the set is already initiated and this is a new node, verify it is present in the replica set's configuration and there are no typos in the host names: > // send ...
Replication
MongoDB supports asynchronous replication of data between servers for failover and redundancy. Only one server (in the set/shard) is active for writes (the primary, or master) at a given time this is to allow strong consistent (atomic) operations. One can optionally send read ...
Replication Internals
master mongod instance, the {{local}} database will contain a collection, {{oplog.$main}}, which stores a highlevel transaction log. The transaction log essentially describes all actions performed by the user, such as "insert this object into this collection." Note that the oplog is not a lowlevel redo log ...
Replication Oplog Length
Replication uses an operation log ("oplog") to store write operations. These operations replay asynchronously on other nodes. The length of the oplog is important if a secondary is down. The larger the log, the longer the secondary can be down and still recover. Once the oplog has ...
Resyncing a Very Stale Replica Set Member
Error RS102 MongoDB writes operations to an oplog.&nbsp; For replica sets this data is stored in collection local.oplog.rs.&nbsp; This is a capped collection and wraps when full "RRD"style.&nbsp; Thus, it is important that the oplog collection is large enough to buffer ...
Retrieving a Subset of Fields
default on a find operation, the entire object is returned. However we may also request that only certain fields be returned. This is somewhat analogous to the list of \column specifiers in a SQL SELECT statement (projection). // select z from things where x ...
Roadmap
Please see jira https://jira.mongodb.org/browse/SERVER#selectedTab=com.atlassian.jira.plugin.system.project%3Aroadmappanel
Ruby External Resources
number of good resources appearing all over the web for learning about MongoDB and Ruby. A useful selection is listed below. If you know of others, do let us know. Screencasts Introduction to MongoDB Part I http://www.teachmetocode.com/screencasts ...
Ruby Language Center
an overview of the available tools and suggested practices for using Ruby with MongoDB. Those wishing to skip to more detailed discussion should check out the Ruby Driver Tutorial http://api.mongodb.org/ruby/current/file.TUTORIAL.html, Getting started with Rails Rails ...
Ruby Tutorial
tutorial gives many common examples of using MongoDB with the Ruby driver. If you're looking for information on data modeling, see MongoDB Data Modeling and Rails. Links to the various object mappers are listed on our object mappers page http://www.mongodb.org ...

S

Scala Language Center
Casbah http://github.com/mongodb/casbah Casbah is the officially supported Scala driver for MongoDB. It provides wrappers and extensions to the Java driver DOCS:Java Language Center meant to allow a more Scalafriendly interface to MongoDB. It supports serialization/deserialization of common ...
Schema Design
Schema design in MongoDB is very different from schema design in a relational DBMS. However it is still very important and the first step towards building an application. In relational data models, conceptually there is a "correct" design for a given entity relationship model ...
scons
Use scons http://www.scons.org/ to build MongoDB and related utilities and libraries.&nbsp; See the SConstruct file for details. Run {{scons \help}} to see all options. Targets Run {{scons <target>}}. {{scons .}} {{scons all}} {{scons mongod}} build ...
Scripting the shell
MongoDB shell is not just an interactive shell, it can also be scripted using JS files. In addition to specifying a Javascript file (.js) you can also use {{\eval}} with a snippet of JS. Using the shell this way allows for tasks to be performed ...
Searching and Retrieving
Security and Authentication
MongoDB includes basic authentication functionality. By default, authentication is off. When off, it is then required that one runs the database in a trusted (network restricted) environment. Authentication is not available with sharding before v2.0. Older sharded environments must run with the database in a trusted ...
Server-side Code Execution
Mongo supports the execution of code inside the database process. Map/Reduce MongoDB supports Javascriptbased map/reduce operations on the server. See the map/reduce documentation DOCS:MapReduce for more information. Using {{db.eval()}} Use map/reduce instead ...
Server-Side Processing
serverStatus Command
serverStatus command provides very useful diagnostic information for a mongod instance. From the shell: > db.commandHelp("serverStatus") help for: serverStatus returns lots of administrative server statistics > db.serverStatus() Field Example Value Explanation host my.node.com The hostname of this server version ...
setParameter Command
Setting Runtime Parameters This command allows changes to be made at runtime for some internal options as well some of the Command Line Parameters. This command was added in 1.8 but some of the options have changed since then. Please pay attention to the version when they were ...
Shard Ownership
shard ownership we mean which server owns a particular key range. Early draft/thoughts will change: Contract the master copy of the ownership information is in the config database mongos instances have cached info on which server owns a shard ...
Sharding
MongoDB scales horizontally via an autosharding (partitioning) architecture. MongoDB sharding provides: Automatic balancing for changes in load and data distribution Easy addition of new machines without down time Scaling to one thousand nodes No single points ...
Sharding Administration
Here we present a list of useful commands for obtaining information about a sharding cluster. To set up a sharding cluster, see the docs on sharding configuration DOCS:Configuring Sharding. Identifying a Shard Cluster // Test if we're speaking to a mongos process ...
Sharding and Failover
properlyconfigured MongoDB shard cluster will have no single point of failure. This document describes the various potential failure scenarios of components within a shard cluster, and how failure is handled in each situation. 1. Failure of a {{mongos}} routing process. One {{mongos ...
Sharding Config Schema
Sharding configuration schema. This lives in the config servers. The config server data is the most important data in your entire cluster. Back it up before doing config server maintenance. Collections version This is a singleton that contains the current metadata version number ...
Sharding Design
concepts config database \ the top level database that stores information about servers and where things live. shard. this can be either a single server or a replica pair. database \ one top level namespace. a database can be partitioned or not chunk \ a region ...
Sharding FAQ
See also: Intro FAQ FAQ DOCS:Developer FAQ DOCS:Replica Set FAQ Should I start out with sharded or with a nonsharded MongoDB environment? We suggest starting unsharded for simplicity and quick startup unless your initial ...
Sharding Internals
section includes internal implementation details for MongoDB auto sharding.&nbsp; See also the main sharding documentation. DOCS:Sharding Note: some internals docs could be out of date \\ if you see that let us know so we ...
Sharding Introduction
MongoDB supports an automated sharding/partitioning architecture, enabling horizontal scaling across multiple nodes. For applications that outgrow the resources of a single database server, MongoDB can convert to a sharded cluster, automatically managing failover and balancing of nodes, with few ...
Sharding Limits
Security Authentication mode will be available with sharding as of v2.0. See SERVER921 https://jira.mongodb.org/browse/SERVER921 for details. Differences from Unsharded Configurations Prior to v2.0, sharding must be run in trusted security mode, without explicit security DOCS:Security and Authentication ...
Sharding Use Cases
What specific use cases do we want to address with db partioning (and other techniques) that are challenging to scale? List here for discussion. video site (e.g., youtube) (also, GridFS scaleup) seems straightforward: partition by video for related videos ...
Simple Initial Sharding Architecture
Overview This is a sample sharding architecture that is a good starting point for building your cluster. Goal Two datacenters (East=primary, West=backup/DR) Data Tier (MongoDB) 3 shards 3 nodes per shard 9 hosts total ...
Slide Gallery
Slides and Video
Upcoming Events http://www.10gen.com/events Presentations from past conferences http://www.10gen.com/presentations Some past webinars Analytics MongoDB Analytics for Online Advertising at Magnetic http://www.10gen.com/presentations/webinar/mongodbanalyticsforonlineadvertisingatmagnetic DevOps Data Center Awareness ...
Smoke Tests
Test Organization # {{dbtests/.cpp}} has C unit tests # {{jstests/.js}} has core tests # {{jstests/repl/.js}} has replication tests # {{jstests/sharding/.js}} has sharding tests # {{slowNightly/js}} has tests that take ...
Sorting and Natural Order
Natural order" is defined as the database's native ordering of objects in a collection. When executing a {{find()}} with no parameters, the database returns objects in forward natural order. For standard tables, natural order is not particularly useful because, although the order is often close to insertion ...
Source Code
Source for MongoDB and mongodb.org supported drivers is open source and hosted at Github http://github.com/mongodb. Mongo Database http://github.com/mongodb/mongo/tree/master (includes C\ driver) Python Driver http://github.com/mongodb/mongopythondriver/tree ...
Spec, Notes and Suggestions for Mongo Drivers
Assume that the BSON DOCS:BSON objects returned from the database may be up to 16MB. This size may change over time. See Also Driver Requirements DOCS:Mongo Driver Requirements BSON DOCS:BSON The main Database Internals ...
Splitting Shard Chunks
MongoDB uses two key operations to facilitate sharding split and migrate. Migrate moves a chunk (the data associated with a key range) to another shard. This is done as needed to rebalance. Split splits a chunk into two ranges; this is done to assure no one chunk ...
SQL to Aggregation Framework Mapping Chart
SQL term MongoDB agg framework term WHERE $match GROUP BY $group SELECT $project ORDER BY $sort Note: you can try the agg framework by testing with the v2.1.0 build. Note that 2.1.x is an unstable branch and not for production. Once ...
SQL to Mongo Mapping Chart
MySQL executable Oracle executable Mongo executable {{mysqld}} \\ {{oracle}} \\ {{mongod}} DOCS:Architecture and Components \\ {{mysql}} \\ {{sqlplus}} \\ {{mongo}} \\ MySQL term Mongo term/concept database database DOCS:Databases table collection DOCS:Collections index index ...
SQL to Shell to C++
MongoDB queries are expressed as JSON (BSON DOCS:BSON) objects.&nbsp; This quick reference chart shows examples as SQL, Mongo shell syntax, and Mongo C driver syntax. A query expression in MongoDB (and other things, such as an index key ...
SSD
We are not experts on solid state drives, but tried to provide some information here that would be helpful. Comments very welcome. Multiple MongoDB users have reported good success running MongoDB databases on solid state drives. Write Endurance ...
SSL
Starting and Stopping Mongo
MongoDB is run as a standard program from the command line. Please see Command Line Parameters for more information on those options. For information about running {{mongod}} or {{mongos}} as a service in Windows, see Windows Service. The following examples assume that you ...
Storing Data
Storing Files
Structuring Data for Mongo

T

Tailable Cursors
Tailable cursors are only allowed on capped collections and can only return objects in natural order http://www.mongodb.org/display/DOCS/SortingandNaturalOrder. Tailable queries never use indexes. A tailable cursor "tails" the end of a capped collection, much like ...
Technical Support
Free Support Forum http://groups.google.com/group/mongodbuser IRC Chat and Support irc://irc.freenode.net/#mongodb Commercial Support http://www.10gen.com/support
The Database and Caching
relational databases, object caching is usually a separate facility (such as memcached), which makes sense as even a RAM page cache hit is a fairly expensive operation with a relational database (joins may be required, and the data must be transformed into an object representation ...
The Linux Out of Memory OOM Killer
Linux out of memory killer kills processes using too much memory. On a kill event you will see a line such as the following in the system log file: Feb 13 04:33:23 hostm1 kernel: 279318.262555 mongod invoked oomkiller ...
Timestamp data type
normal Date Dates datatype. This is a special type for internal MongoDB use. BSON http://bsonspec.org/ includes a timestamp data type with special semantics in MongoDB. Timestamps are stored as 64 bit values which, on a single {{mongod}}, are guaranteed unique. The first ...
Too Many Open Files
you receive the error "too many open files" or "too many open connections" in the mongod log, there are a couple of possible reasons for this. First, to check what file descriptors are in use, run lsof (some variations shown below): lsof grep ...
Tools and Libraries
Talend Adapters https://github.com/adrienmogenet
TreeNavigation
Follow @mongodb http://www.twitter.com/mongodb MongoDB Pittsburgh http://www.10gen.com/events/mongodbpgh May 15 MongoNYC http://www.10gen.com/events/mongonyc May 23 MongoDB Paris http://www.10gen.com/events/mongodbparis Jun 14 MongoDB UK ...
Trees in MongoDB
best way to store a tree usually depends on the operations you want to perform; see below for some different options.&nbsp; In practice, most developers find that one of the "Full Tree in Single Document", "Parent Links", and "Array of Ancestors" patterns ...
Troubleshooting
mongod process "disappeared" Scenario here is the log ending suddenly with no error or shutdown messages logged. On Unix, check /var/log/messages: $ sudo grep mongod /var/log/messages $ sudo grep score /var/log/messages Socket ...
Troubleshooting MapReduce
Tips on troubleshooting map/reduce. Troubleshooting the {{map}} function We can troubleshoot the map function in the shell by defining a test {{emit}} function in the shell and having it print out trace information. For example suppose we have some data: > db.articles.find ...
Troubleshooting the PHP Driver
Tutorial
Running MongoDB First, run through the Quickstart guide for your platform to get Mongo installed. Getting A Database Connection Let's now try manipulating the database with the database shell DOCS:mongo The Interactive Shell . (We could perform similar ...
Tweaking performance by document bundling during schema design
Note: this page discusses performance tuning aspects if you are just getting started skip this for later. If you have a giant collection of small documents that will require significant tuning, read on. During schema design DOCS:Schema Design one consideration ...
two-phase commit
common problem with nonrelational database is that it is not possible to do transactions across several documents. When executing a transaction composed of several sequential operations, some issues arise: Atomicity: it is difficult to rollback changes by previous operations if one fails. Isolation: changes ...

U

Ubuntu and Debian packages
Please read the notes on the Downloads page.&nbsp; 10gen publishes aptgettable packages.&nbsp; Our packages are generally fresher than those in the Debian or Ubuntu repositories.&nbsp; We publish stable releases in our repository, under the name mongodb10gen ...
UI
Spec/requirements for a future MongoDB admin UI. list databases repair, drop, clone? collections validate(), datasize, indexsize, clone/copy indexes queries explain() output security: view users, adjust see replication status of slave and master ...
Updates
Updating
MongoDB supports atomic, inplace updates as well as more traditional updates for replacing an entire document. update() {{update()}} replaces the document matching criteria entirely with objNew. If you only want to modify some fields, you should use ...
Updating Data in Mongo
Updating a Document in the mongo Shell with {{save()}} As shown in the previous section, the {{save()}} method may be used to save a new document to a collection. We can also use {{save()}} to update an existing document in a collection. Continuing with the example database from ...
Upgrading from a Non-Sharded System
mongod}} process can become part of a sharded cluster without any change to that process or downtime. If you haven't done so yet, feel free to have a look at the Sharding Introduction http://www.mongodb.org/display/DOCS/ShardingIntroduction to familiarize yourself ...
Upgrading to 1.8
First, upgrade your shell ({{mongo}}) to the 1.8.x shell. Upgrading Replica Sets 1.8.x secondaries can replicate from 1.6.x primaries. 1.6.x secondaries cannot replicate from 1.8.x primaries. Thus, the trick is to replace all of your secondaries ...
Upgrading to Replica Sets
Upgrading From a Single Server If you're running MongoDB on a single server, upgrading to replica sets is trivial (and a good idea\!). First, we'll initiate a new replica set with a single node. We need a name for the replica set in this case we're ...
Use Case - Session Objects
MongoDB is a good tool for storing HTTP session objects. One implementation model is to have a sessions collection, and store the session object's \id value in a browser cookie. With its updateinplace design and general optimization to make updates fast, the database is efficient ...
Use Cases
See also the Production Deployments DOCS:Production Deployments page for a discussion of how companies like Craigslist, Shutterfly, foursquare, bit.ly, SourceForge, etc. use MongoDB. Well Suited Archiving http://blog.mongodb.org/post/1200539426/archivingagoodmongodbusecase and event logging http://blog.mongodb.org ...
User Feedback
I just have to get my head around that mongodb is really \this\ good" &nbsp; \muckster, #mongodb "Guys at Redmond should get a long course from you about what is the software development and support :) " &nbsp; \kunthar@gmail.com, mongodbuser list ...
Using a Large Number of Collections
technique one can use with MongoDB in certain situations is to have several collections to store information instead of a single collection.&nbsp; By doing this, certain repeating data no longer needs to be stored in every object, and an index on that key may be eliminated ...
Using Multikeys to Simulate a Large Number of Indexes
One way to work with data that has a high degree of options for queryability is to use the multikey DOCS:Multikeys indexing feature where the keys are objects.&nbsp; For example: > x = { ... id : "abc", ... cost : 33, ... attribs : ... , ... , ... , ... ... }; > db.foo.insert(x); > db.foo.ensureIndex( ); > db.foo.find ...

V

v0.8 Details
Existing Core Functionality Basic Mongo database functionality: inserts, deletes, queries, indexing. Master / Slave Replication Replica Pairs Serverside javascript code execution New to v0.8 Drivers for Java, C, Python, Ruby. db shell utility ...
Validate Command
Use this command to check that a collection is valid (not corrupt) and to get various statistics. This command scans the entire collection and its indexes and will be very slow on large datasets. option description full Validates everything new in 2.0.0 scandata Validates basics (index ...
Verifying Propagation of Writes with getLastError
Please read the getLastError command page first. A client can await a write operation's replication to N servers (v1.6). Use the getlasterror command with the parameter {{w}}: // examples: db.runCommand( ) db.runCommand( ) db.runCommand( ) db.runCommand( ) If {{w}} is not set, or equals one, the command ...
Version Numbers
MongoDB uses the oddnumbered versions for development releases http://en.wikipedia.org/wiki/Softwareversioning#Oddnumberedversionsfordevelopmentreleases. There are 3 numbers in a MongoDB version: A.B.C A is the major version. This will rarely change and signify very large changes B is the release number. This will include many changes ...
Video & Slides from Recent Events and Presentations
Table of Contents: MongoDB Conferences Oneday conferences hosted by 10gen http://www.10gen.com/. 10gen develops and supports MongoDB. MongoUK Video (June 2010) http://skillsmatter.com/event/cloudgrid/mongouk MongoFR Video (June 2010) http://lacantine.ubicast.eu/categories ...
Viewing and Terminating Current Operation
View Operation(s) in Progress > db.currentOp(); { inprog: { "opid" : 18 , "op" : "query" , "ns" : "mydb.votes" , "query" : " " , "inLock" : 1 } } > > // to include idle connections in report: > db.currentOp(true); Fields: opid an incrementing operation number.&nbsp; Use with killOp(). active ...
Virtualization
Generally MongoDB works very well in virtualized environments, with the exception of OpenVZ. EC2 Compatible. No special configuration requirements. VMWare Some suggest not using overcommit as they may cause issues. Otherwise compatible. Cloning a VM is possible. For example you might ...
Visit the 10gen Offices
Bay Area 10gen's West Coast office is located in downtown Palo Alto. 555 University Ave. Palo Alto, CA 94301 \\ <iframe width="495" height="395" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src ...
VMware CloudFoundry
MongoDB is a supported service on VMware's Cloud Foundry http://www.cloudfoundry.com/. Starting a MongoDB service {{vmc createservice mongodb name MyMongoDB}} Once you create a MongoDB service, you can bind and use it inside of Cloud Foundry applications. Developing ...

W

What is the Compare Order for BSON Types
MongoDB allows objects in the same collection which have values which may differ in type.&nbsp; When comparing values from different types, a convention is utilized as to which value is less than the other.&nbsp; This (somewhat arbitary but well ...
What's New by Version
summary of high level features only. See jira http://jira.mongodb.org/ and release notes DOCS:1.8 Release Notes for full details. 1.4 Geospatial DOCS:Geospatial Indexing Background DOCS:Indexing as a Background Operation indexing directoryperdb Log ...
When to use GridFS
page is under construction When to use GridFS Lots of files. GridFS tends to handle large numbers (many thousands) of files better than many file systems. User uploaded files. When users upload files you tend ...
Why are my datafiles so large?
Why Replica Sets
Replica sets provide five distinct benefits over the use of a single node. A system requiring one or more of the following features should consider using replica sets. Data Redundancy Replica sets provide an automated method for storing ...
Why so many "Connection Accepted" messages logged?
Windows
Windows Quick Links and Reference Center Running MongoDB on Windows See the Quickstart page DOCS:Quickstart Windows for info on how to install and run the database for the first time. Running as a Service See the Windows Service page. The MongoDB Server Get ...
Windows Service
mongod.exe has native support for installing and running as a Windows service. 2.1.1\ This feature is available in mongos.exe as well Servicerelated command line options The main command line options for working with MongoDB as a Windows service are: \install Install as a Windows service, then exit ...
Wireshark Support for MongoDB Protocol
Wireshark http://www.wireshark.org/, an advanced interactive network traffic sniffer, has full support http://wiki.wireshark.org/Mongo for the MongoDB Wire protocol. You can visually inspect MongoDB traffic, do complex filters on specific values of MongoDB ...
Working with Mongo Objects and Classes in Ruby
Writing Drivers and Tools
See Also DOCS:Mongo Query Language mongosniff objcheck command line parameter DOCS:Command Line Parameters
Writing tests
We have three general flavors of tests currently. General guidelines It is important that tests can be run in parallel and still succeed. For example, make sure that: try to use a unique collection name, for example named after the test t = db.jstestscurrentop if checking ...

X

Y

Your Go-to Resource for Running a MongoDB User Group
Tips for Running a Successful User Group Interested in Starting a User Group? Organizing a user group is a fantastic way to meet and learn from other MongoDB fans in your local community. Interested in starting up a user group in your city ...

Z

!@#$

Follow @mongodb

MongoDB Pittsburgh - May 15
MongoNYC - May 23
MongoDB Paris - Jun 14
MongoDB UK - Jun 20
MongoDC - June 26


Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

PLEASE POST QUESTIONS IN THE USER GROUPS FORUM. Post non-question comments and helpful hints here.

blog comments powered by Disqus