Software Development

MongoDB Shell Guide – Operations and Commands

This article is part of our Academy Course titled MongoDB – A Scalable NoSQL DB.

In this course, you will get introduced to MongoDB. You will learn how to install it and how to operate it via its shell. Moreover, you will learn how to programmatically access it via Java and how to leverage Map Reduce with it. Finally, more advanced concepts like sharding and replication will be explained. Check it out here!

1. Introduction

MongoDB shell is the best tool out there to discover MongoDB features and manage every single aspect of your server deployments, instances, databases, collections and documents. It is based on JavaScript language for executing command and queries. Please do not worry if you have little or no knowledge of JavaScript: you will be able to mostly understand every example effortlessly as there is a common pattern to follow.

With JSON being a format to manage document, it is also used to specify commands and queries as well as to return their results. Such unification brings a lot of benefits because JSON is inherently simple, human-friendly and easy to understand.

In this part of the tutorial our intention is to go through most of the commands and queries supported by MongoDB using its shell except the ones related to sharding (will be covered in details in Part 4. MongoDB Sharding Guide) and replication (will be covered in details in Part 5. MongoDB Replication Guide). More advanced topics will be covered in Part 7. MongoDB Security, Profiling, Indexing, Cursors and Bulk Operations Guide.

Each section is dedicated to particular aspect of MongoDB: we start off from Shell Command Helpers, then look at Databases, Collections and Documents, move to Queries and Aggregations, and finish up with Server specific commands.

MongoDB has many internal and experimental commands and those (in most cases) we will not cover. Their usage is limited to very specific scenarios you may never encounter (or their behavior might be unstable).

Next sections assume that your MongoDB server instance is up and running on local machine as described in Part 1. MongoDB Installation – How to install MongoDB.

2. Shell Command Helpers

MongoDB shell provides a couple of command helpers which allow establishing the context and implicitly populating shell variables, including:

  • db: current database context variable
  • rs: replica set context variable
  • sh: sharding context variable

With no command line arguments provided, MongoDB shell by default connects to local MongoDB server instance on port 27017 and database with name test (which may not physically exist on the disk).

Command use <database>
Description Switches current database to <database> and assigns shell variable db to the current database.
Example In MongoDB shell, let us issue the command: use mydb
02.USE
Reference http://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

use <database>

 

Command show dbs

show databases

Description Outputs a list of all databases on the server instance.
Example In MongoDB shell, let us issue the command: show dbs (or show databases)
Reference http://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

show dbs
show databases

 

Command show collections
Description Outputs a list of all collections for current database.
Example In MongoDB shell, let us issue the commands:

  • use local
  • show collections

02.SHOW.COLLECTIONS

Reference http://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

show collections

 

Command show users
Description Outputs a list of users for current database with their roles and custom data (if any).
Example In MongoDB shell, let us issue the command: show users 02.SHOW.USERS
Reference http://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

show users

 

Command show roles
Description Outputs a list of all roles, both user-defined and built-in, for the current database.
Example In MongoDB shell, let us issue the command: show roles 02.SHOW.ROLES

Note: Only a fragment of the output is shown.

Reference http://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

show roles

 

Command show logs
Description Shows the accessible logger names.
Example In MongoDB shell, let us issue the command: show logs 02.SHOW.LOGS
Reference http://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

show logs

Command show log [name]
Description Outputs the last segment of log in memory. If logger name is omitted the global logger will be used as default.
Example In MongoDB shell, let us issue the command: show log global 02.SHOW.LOG

show log [name]

 

Command load(<filename>)
Description Loads and executes a JavaScript file with name filename inside current MongoDB shell environment.
Example Let us prepare the sample db.js script, located inside MongoDB installation folder, which just lists all available databases and outputs their names on a console:

result = db.getSiblingDB( 'admin' )
.runCommand( { listDatabases: 1 } );
for( index in result.databases ) {
    print( result.databases[ index ].name );
}

In MongoDB shell, let us issue the command: load( ‘db.js’ )

02.LOAD

Reference http://docs.mongodb.org/manual/reference/method/load/

load(<filename>)

 

Command help
Description Shows quick help on shell commands.
Example In MongoDB shell, let us issue the command: help 02.HELP
Reference http://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

help

 

With MongoDB shell, there are at least two ways to run commands:

  • using the generic db.runCommand() function call
  • using the more convenient db.<command> or db.<collection>.<command> wrapper function calls

In most cases the second option is much more readable and that will be the choice for our examples in the following sections. In most cases both options will be demonstrated side by side (if applicable) so you will be able to pick your favorite way to run commands. Please notice that not all commands do have MongoDB shell wrappers and as such, they can be run with db.runCommand() function call only.

Command db.runCommand(<command>)
Description Provides a helper to run specified database commands. This is the preferred method to issue database commands, as it provides a consistent interface between the shell and drivers.
Example In MongoDB shell, let us issue the command: db.runCommand( { buildInfo: 1 } )

02.DB.RUNCOMMAND

Reference http://docs.mongodb.org/manual/reference/method/db.runCommand/

db.runCommand(<command>)

 

Command version()
Description Returns the current version of the MongoDB shell instance.
Example In MongoDB shell, let us issue the command: version() 02.VERSION
Reference http://docs.mongodb.org/manual/reference/method/version/

version()

 

Command getHostName()

hostname()

Description Returns the hostname of the system running the MongoDB shell.
Example In MongoDB shell, let us issue the command: hostname() (or getHostName()) 02.HOSTNAME
Reference http://docs.mongodb.org/manual/reference/method/hostname/

http://docs.mongodb.org/manual/reference/method/getHostName/

getHostName()
hostname()

 

Command getMemInfo()
Description Returns a document with two fields that report the amount of memory (in megabytes) used by the JavaScript MongoDB shell:

  • resident: the subset of a memory currently stored in physical RAM
  • virtual: a working memory, typically residing on both disk and in physical RAM
Example In MongoDB shell, let us issue the command: getMemInfo() 02.GETMEMINFO
Reference http://docs.mongodb.org/manual/reference/method/getMemInfo/

getMemInfo()

 

Command quit()
Description Exits the current shell session.
Reference http://docs.mongodb.org/manual/reference/method/quit/

quit()

 

3. Databases

Database is a top-level data container in MongoDB which holds one or more collections of documents. For every database MongoDB creates physical file (or files) on a disk, aggressively pre-allocating data files to reserve the space and avoid file system fragmentation.

The data file names follow the pattern: the first data file has name <databasename>.0, the next one <databasename>.1 and so on. The size of first pre-allocated file is 64 megabytes, the second one has size 128 megabytes, next one 256 megabytes, and so on, up to maximum size of 2 gigabytes (at this point all subsequent files will be 2 gigabytes in size). One thing to keep in mind, MongoDB will not permanently create a database until the data is inserted into it.

By default, MongoDB also creates the journal files, which store write operations on disk prior to they are being applied to databases.

Command db.help()
Description Show help for database methods.
Example In MongoDB shell, let us issue the command: db.help() 02.DB.HELP

Note: Only a fragment of the output is shown.

Reference http://docs.mongodb.org/manual/reference/method/db.help/#db.help

db.help()

 

Command db.commandHelp(<command>)
Description Displays the help information for particular command <command> with examples of usage and expecting parameters.
Example In MongoDB shell, let us issue the command: db.commandHelp(‘filemd5’) 02.DB.COMMANDHELP
Reference http://docs.mongodb.org/manual/reference/method/db.commandHelp/

db.commandHelp(<command>)

 

Command db.getName()
Description Returns the current database name.
Example In MongoDB shell, let us issue the command: db.getName() 02.DB.GETNAME
Reference http://docs.mongodb.org/manual/reference/method/db.getName/

db.getName

 

Command db.getSiblingDB(<database>)
Description Returns another database without modifying the db variable in the shell environment. It can be used as an alternative to the use <database> helper (see please Shell Command Helpers).
Example In MongoDB shell, let us issue the command: db.getSiblingDB(‘admin’).getName() 02.DB.GETSIBLINGDB
Reference http://docs.mongodb.org/manual/reference/method/db.getSiblingDB/

db.getSiblingDB(<database>)

 

Every MongoDB server instance has its own local database, which stores data used in the replication process, and other instance-specific data. The local database is not touched by replication: collections in the local database are never replicated (Part 5. MongoDB Replication Guide talks more about replication). Also, there is an admin database – a privileged database which users must have access to in order to run certain administrative commands.

To run the command in context of admin database, the following options are available:

  • use admin
    db.runCommand( <command> )
    

    Please notice that the current database will be switched to admin.

  • db.getSiblingDB( 'admin' ) .runCommand( <command> )

    A bit more verbose chained calls but current database will not be switched and stays unchanged.

  • db.adminCommand( <command> )

    A shortcut to db.getSiblingDB( ‘admin’ ) .runCommand( <command> ).

Command listCommands
Wrapper db.listCommands()
Description Displays a list of all database commands with examples of usage and expecting parameters. The commands which require administrative privileges are marked as adminOnly.
Example In MongoDB shell, let us issue the command: db.listCommands() 02.DB.LISTCOMMANDS
Alternatively, let us run the same command using runCommand() call: db.runCommand( { listCommands: 1 } )Note: Only a fragment of the output is shown.
Reference http://docs.mongodb.org/manual/reference/command/listCommands/

http://docs.mongodb.org/manual/reference/method/db.listCommands/

listCommands

 

Command listDatabases
Description This command provides a list of existing databases together with basic statistics about them. It should be run in context of admin database.
Example In MongoDB shell, let us issue the command: db.getSiblingDB(‘admin’).runCommand( { listDatabases: 1 } ) 02.DB.LISTDATABASES
Reference http://docs.mongodb.org/manual/reference/command/listDatabases/

listDatabases

 

Command copydb
Parameters
{ 
    fromhost: <hostname>,
    fromdb: <database>,
    todb: <database>,
    slaveOk: <true|false>,
    username: <username>,
    nonce: <nonce>,
    key: <key> 
}
Wrapper db.copyDatabase(<fromdb>, <todb>, <fromhost>, <username>, <password>)
Description Copies a database from a remote host to the current host or copies a database to another database within the current host. It should be run in context of admin database.
Example In MongoDB shell, let us issue the command:

db.getSiblingDB('admin').runCommand( { 
    copydb: 1, 
    fromdb: 'test', 
    todb: 'test2' 
} )

02.DB.COPYDB

Alternatively, let us run the same command using MongoDB shell wrapper: db.copyDatabase( ‘test’, ‘test2’ )

02.DB.COPYDATABASE
The consecutive run of show dbs outputs the new database test2 in the list after each command run.

Reference http://docs.mongodb.org/manual/reference/command/copydb/

http://docs.mongodb.org/manual/reference/method/db.copyDatabase/

copydb

 

Command dropDatabase
Wrapper db.dropDatabase()
Description Removes the current database.It should be run in context of admin database.
Example In MongoDB shell, let us issue the commands:

    • use test2
    • db.dropDatabase()

02.DB.DROPDATABASE
Alternatively, let us run the same command using runCommand() call:

  • use test2
  • db.runCommand( { dropDatabase: 1 } )

Or even shortest version: db.getSiblingDB( ‘test2’ ).dropDatabase()

Reference http://docs.mongodb.org/manual/reference/command/dropDatabase/

http://docs.mongodb.org/manual/reference/method/db.dropDatabase/

dropDatabase

 

Command clone
Wrapper db.cloneDatabase( <hostname>[:<port>] )
Description This command clones a database with the same name as the current database from a remote MongoDB instance running on <hostname> andport <port> to the current host.
Example Assuming there in another instance of MongoDB server running on port 27018, let us issue the command in the shell: db.cloneDatabase( ‘localhost:27018’ ) 02.DB.CLONEDATABASE

Alternatively, let us run the same command using runCommand() call: db.runCommand( { clone: ‘localhost:27018’ } )

Reference http://docs.mongodb.org/manual/reference/command/clone/

http://docs.mongodb.org/manual/reference/method/db.cloneDatabase/

clone

 

Command repairDatabase
Parameters
{ 
    preserveClonedFilesOnFailure: <true|false>,
    backupOriginalFiles: <true|false> 
}
Wrapper db.repairDatabase()
Description Checks and repairs any errors and inconsistencies with the data storage of current database.
Example In MongoDB shell, let us issue the command: db.repairDatabase()

02.DB.REPAIRDATABASE

Alternatively, let us run the same command using runCommand() call: db.runCommand( { repairDatabase: 1 } )

Reference http://docs.mongodb.org/manual/reference/command/repairDatabase/

http://docs.mongodb.org/manual/reference/method/db.repairDatabase/

repairDatabase

 

Command fsync
Parameters
{ 
    async: <true|false>, 
    lock: <true|false> 
}
Wrapper db.fsyncLock() / db.fsyncUnlock()
Description Flushes all pending writes from the storage layer to disk. Optionally, it can lock the server instance and block write operations for the purpose of capturing backups.It should be run in context of admin database.
Example In MongoDB shell, let us issue the commands:

  • db.fsyncLock ()
  • db.fsyncUnlock()

02.DB.FSYNCLOCK

Alternatively, let us run the same command using runCommand() call:

  • db.adminCommand( { fsync: 1, lock: true } )
  • db.fsyncUnlock()
Reference http://docs.mongodb.org/manual/reference/command/fsync/

http://docs.mongodb.org/manual/reference/method/db.fsyncLock/

http://docs.mongodb.org/manual/reference/method/db.fsyncUnlock/

fsync

 

Command dbStats
Parameters
{ 
    scale: <scale>
}
Wrapper db.stats( <scale> )
Description Outputs the storage statistics for a given database.
Example In MongoDB shell, let us issue the command: db.stats()

02.DB.STATS

Alternatively, let us run the same command using runCommand() call: db.runCommand( { dbStats: 1 } )

Reference http://docs.mongodb.org/manual/reference/command/dbStats/

http://docs.mongodb.org/manual/reference/method/db.stats/

dbStats

4. Collections

Collections are the containers of MongoDB documents that share one or more indexes. For the users familiar with RDBMS concepts, a collection is the equivalent of a table. Collection belongs to a single database and do not enforce any schema on containing documents. There is no limit on number of documents any individual collection can contain unless it is a special type of collection called capped collection: a fixed-sized collection that automatically overwrites its oldest entries when it reaches its maximum size.

Together with database name, collections form a namespace: database name concatenated with collection name using period ‘.’ character, for example:

  • test.collection1
  • test.collection1.subcollection1

Additionally to user-defined collections, MongoDB stores system information in collections that use the <database>.system.* namespace and are reserved for internal use. The admin database (see please Databases section) includes following system collections:

  • admin.system.roles
  • admin.system.users
  • admin.system.version

Each user database has following system collections defined:

  • <database>.system.namespaces
  • <database>.system.indexes
  • <database>.system.profile
  • <database>.system.js

In this section we will not explore system collections directly but if you are interested in getting more details, please refer to the official documentation.

Command db.<collection>.help()
Description Show help on collection methods. The <collection> can be the name of an existing collection or a non-existing collection.
Example In MongoDB shell, let us issue the command: db.mycoll.help()

02.DB.COLLECTION.HELP

Note: Only a fragment of the output is shown.

db.<collection>.help()

 

Command db.getCollectionNames()
Description Returns all collections in the current database.
Example In MongoDB shell, let us issue the command: db.getCollectionNames()

02.DB.GETCOLLECTIONNAMES

Reference http://docs.mongodb.org/manual/reference/method/db.getCollectionNames/

db.getCollectionNames()

 

Command db.getCollection(<name>)
Description Returns a collection name. This is useful for a collection whose name might interact with the shell itself (for example, begins with _ or has the same name as built-in database command).
Example In MongoDB shell, let us issue the command: db.getCollection( ‘system.indexes’ )

02.DB.GETCOLLECTION

Reference http://docs.mongodb.org/manual/reference/method/db.getCollection/

db.getCollection(<name>)

 

Command create
Parameters
{ 
    create: <collection>,
    capped: <true|false>,
    autoIndexId: <true|false>,
    size: <max_size>,
    max: <max_documents>,
    flags: <0|1>
}
Wrapper db.createCollection( <collection>, {capped: <true|false>, autoIndexId: <true|false>, size: <number>, max: <number>} )
Description Explicitly creates a new collection <collection>.
Example In MongoDB shell, let us issue the command: db.createCollection( ‘mycoll’, { capped: false } )

02.DB.CREATECOLLECTION

Alternatively, let us run the same command using runCommand() call: db.runCommand( { create: ‘mycoll’, capped: false } )

The consecutive call to db.getCollectionNames() outputs the newly created collections.

Reference http://docs.mongodb.org/manual/reference/command/create/

http://docs.mongodb.org/manual/reference/method/db.createCollection/

create

 

Command drop
Parameters
{ 
    drop: <collection> 
}
Wrapper db.<collection>.drop()
Description Removes the specified collection <collection> from the database.
Example In MongoDB shell, let us issue the commands:

  • db.createCollection( ‘mycoll’ )
  • db.mycoll.drop()

02.DB.COLLECTION.DROP

Alternatively, let us run the same command using runCommand() call: db.runCommand( { drop: ‘mycoll’ } )

Reference http://docs.mongodb.org/manual/reference/command/drop/

http://docs.mongodb.org/manual/reference/method/db.collection.drop/

drop

 

Command renameCollection
Parameters
{ 
    renameCollection: <source_namespace>, 
    to: <target_namespace>, 
    dropTarget: <true|false> 
}
Wrapper db.<collection>. renameCollection(<target>, <dropTarget>)
Description Changes the name of an existing collection <collection>.It should be run in context of admin database.
Example In MongoDB shell, let us issue the commands:

  • db.createCollection( ‘mycoll’ )
  • db.mycoll.renameCollection( ‘mycoll2’ )

02.DB.COLLECTION.RENAMECOLLECTION

Alternatively, let us run the same command using runCommand() call: db.adminCommand( { renameCollection: ‘test.mycoll’, to: ‘test.mycoll2’ } )

Reference http://docs.mongodb.org/manual/reference/command/renameCollection/

http://docs.mongodb.org/manual/reference/method/db.collection.renameCollection/

renameCollection

 

Command validate
Parameters
{
    validate: <collection>,
    full: <true|false>
}
Wrapper db.<collection>.validate( <full> )
Description Checks the structures within a collection <collection> for correctness by scanning the collection’s data and indexes. The command returns information regarding the on-disk representation of the collection.
Example In MongoDB shell, let us issue the commands:

  • db.createCollection( ‘mycoll’ )
  • db.mycoll.validate()

02.DB.COLLECTION.VALIDATE

Alternatively, let us run the same command using runCommand() call: db.runCommand( { validate: ‘mycoll’ } )

Reference http://docs.mongodb.org/manual/reference/command/validate/

http://docs.mongodb.org/manual/reference/method/db.collection.validate/

validate

 

Command cloneCollection
Parameters
{ 
    cloneCollection: <namespace>, 
    from: <hostname>, 
    query: { <query> } 
}
Wrapper db.cloneCollection(<from>, <collection>, <query>)
Description Copies a collection <collection> from a remote host to the current host.
Example Assuming there in another instance of MongoDB server running on port 27018, let us issue the command in the shell: db.cloneCollection( ‘localhost:27018’, ‘test.mycoll’ )

02.DB.CLONECOLLECTION

Alternatively, let us run the same command using runCommand() call: db.runCommand( { cloneCollection: ‘test.mycoll’, from: ‘localhost:27018’ } )

Reference http://docs.mongodb.org/manual/reference/command/cloneCollection/

http://docs.mongodb.org/manual/reference/method/db.cloneCollection/

cloneCollection

 

Command cloneCollectionAsCapped
Parameters
{ 
    cloneCollectionAsCapped: <existing collection>, 
    toCollection: <capped collection>, 
    size: <capped size> 
}
Description Creates a new capped collection <capped collection> from an existing <existing collection>, non-capped collection within the same database. The operation does not affect the original non-capped collection.
Example In MongoDB shell, let us issue the commands:

db.createCollection( 'mycoll' )
db.runCommand( { 
    cloneCollectionAsCapped: 'mycoll', 
    toCollection: 'mycollcapped', 
    size: 10 
} )

02.DB.CLONECOLLECTIONASCAPPED

Reference http://docs.mongodb.org/manual/reference/command/cloneCollectionAsCapped/

cloneCollectionAsCapped

 

Command convertToCapped
Parameters
{
    convertToCapped: <collection>, 
    size: <capped size> 
}
Description Converts an existing, non-capped collection <collection> to a capped collection within the same database.
Example In MongoDB shell, let us issue the commands:

db.createCollection( 'mycoll' )
db.runCommand( { 
    convertToCapped: 'mycoll', 
    size: 10 
} )

02.DB.CONVERTTOCAPPED

Reference http://docs.mongodb.org/manual/reference/command/convertToCapped/

convertToCapped

 

Command collStats
Parameters
{ 
    collStats: <collection>, 
    scale : <scale> 
}
Wrapper
db.<collection>.stats(<scale>)
db. <collection>.totalSize()
db. <collection>.dataSize()
db. <collection>.totalIndexSize()
db. <collection>.storageSize()
Description Returns a variety of storage statistics for a given collection <collection>.
Example In MongoDB shell, let us issue the command: db.mycoll.stats()

02.DB.COLLECTION.STATS

Alternatively, let us run the same command using runCommand() call: db.runCommand( { collStats: ‘mycoll’ } )

Reference http://docs.mongodb.org/manual/reference/command/collStats/

http://docs.mongodb.org/manual/reference/method/db.collection.stats/

http://docs.mongodb.org/manual/reference/method/db.collection.totalSize/

http://docs.mongodb.org/manual/reference/method/db.collection.dataSize/

http://docs.mongodb.org/manual/reference/method/db.collection.totalIndexSize/

http://docs.mongodb.org/manual/reference/method/db.collection.storageSize/

http://docs.mongodb.org/manual/reference/method/db.printCollectionStats/

db.printCollectionStats()

 

Command createIndexes
Parameters
{
    createIndexes: <collection>,
    indexes: [
        {
            key: {
                <key-value_pair>,
                <key-value_pair>,
                ...
            },
            name: <index_name>,
            <option1>,
            <option2>,
            ...
        },
        { ... },
        { ... }
    ]
}
Wrapper db.<collection>. ensureIndex(<keys>, <options>)
Description Builds one or more indexes on a collection <collection>.
Example In MongoDB shell, let us issue the command: db.mycoll.ensureIndex( { content: “text” } )

02.DB.COLLECTION.ENSUREINDEX

Alternatively, let us run the same command using runCommand() call:

db.runCommand( { 
    createIndexes: 'mycoll',
    indexes: [
        {
            key: { content: 'text' },
            name: 'myindex'
        }
    ]
} )
Reference http://docs.mongodb.org/manual/reference/command/createIndexes/

http://docs.mongodb.org/manual/reference/method/db.collection.ensureIndex/

createIndexes

 

Command dropIndexes
Parameters
{ 
    dropIndexes: <collection>, 
    index: <index> 
}
Wrapper db.<collection>.dropIndexes()

db.<collection>.dropIndex(<index>)

Description Drops one or all indexes from the collection <collection>. To drop all indexes, pass the ‘*’ as the <index> value.
Example In MongoDB shell, let us issue the commands:

db.mycoll.ensureIndex( { content: "text" } )
db.mycoll.dropIndexes()

02.DB.COLLECTION.DROPINDEXES

Alternatively, let us run the same command using runCommand() call: db.runCommand( { dropIndexes: ‘mycoll’, index: ‘*’ } )

Reference http://docs.mongodb.org/manual/reference/command/dropIndexes/

http://docs.mongodb.org/manual/reference/method/db.collection.dropIndexes/

http://docs.mongodb.org/manual/reference/method/db.collection.dropIndex/

dropIndexes

 

Command reIndex
Parameters
{ 
    reIndex: <collection>
}
Wrapper db.<collection>.reIndex()
Description Drops all indexes on a collection <collection> and recreates them. This operation may be expensive for collections that have a large amount of data and/or a large number of indexes.
Example In MongoDB shell, let us issue the command: db.mycoll.reIndex()

02.DB.COLLECTION.REINDEX

Alternatively, let us run the same command using runCommand() call: db.runCommand( { reIndex: ‘mycoll’ } )

Reference http://docs.mongodb.org/manual/reference/command/reIndex/

http://docs.mongodb.org/manual/reference/method/db.collection.reIndex/

reIndex

 

Command compact
Parameters
{ 
    compact: <collection>
}
Description Rewrites and defragments all data in a collection <collection>, as well as all of the indexes on that collection.
Example In MongoDB shell, let us issue the command: db.runCommand( { compact: ‘mycoll’ } )

02.DB.COMPACT

Reference http://docs.mongodb.org/manual/reference/command/compact/

compact

 

Command collMod
Parameters
{
    collMod: <collection> , 
    <flag> : <value> 
}
Description Makes it possible to add flags to a collection <collection> to modify its behavior.
Example In MongoDB shell, let us issue the command: db.runCommand( { collMod: ‘mycoll’, usePowerOf2Sizes : true } )

02.DB.COLLMOD

Reference http://docs.mongodb.org/manual/reference/command/collMod/

collMod

 

Command db.<collection>.isCapped()
Description Returns true if the collection <collection> is a capped collection, otherwise returns false.
Example In MongoDB shell, let us issue the command: db.mycoll.isCapped()

02.DB.COLLECTION.ISCAPPED

Reference http://docs.mongodb.org/manual/reference/method/db.collection.isCapped/

db.isCapped

 

Command db.<collection>.copyTo(<newCollection>)
Description Copies all documents from collection <collection> into new collection <newCollection> using server-side JavaScript. If collection <newCollection> does not exist, it will be created. The command returns the number of documents copied (or 0 if source collection is empty).
Example In MongoDB shell, let us issue the commands:

db.createCollection( 'mycoll' )
db.mycoll.copyTo( 'mycollcopy' )

02.DB.COLLECTION.COPYTO

Reference http://docs.mongodb.org/manual/reference/method/db.collection.copyTo/

db.copyTo

 

5. Documents

In MongoDB the data is represented and stored as a JSON documents: field and value pairs. More precisely, MongoDB uses binary JSON (BSON) to store serialized documents on a disk but for the user it looks like regular JSON (at least, inMongoDB shell). The range of supported filed data types is quite impressive (please refer to BSON data types reference):

  • Double
  • String
  • Object
  • Array
  • Binary Data
  • Undefined
  • Object Id
  • Boolean
  • Date
  • Null
  • Regular Expression
  • JavaScript (with/without scope)
  • 32-bit integer
  • 64-bit integer
  • Timestamp

Other documents (so called embedded documents), arrays, arrays of documents and references are supported as well.

The field names have couple of restrictions:

  • The field with name _id is reserved for use as a primary key and must be unique in whole collection (it is immutable and may be of any type other than an array). This field is always the first field in the document.
  • The field names cannot start with the dollar sign ‘$’ character and cannot contain the dot ‘.’ character. Those are reserved.

For example, the simple document representing a Book may look like this:

{
    "_id": ObjectId("536a5fe20ad33fcab3abfc0e"),
    "title": "MongoDB In Action",
    "author": { "firstName": "Kyle", "lastName": "Banker" },
    "isbn": "978-1935182870",
    "published": new Date("Dec 16, 2011" ),
    "categories": [ "NoSQL", "Document Databases" ]
}

References (DBRefs) are the pointers from one document to another (using the value of the document’s _id field, collection name, and, optionally, its database name):

{ 
    "$ref" : <collection>, 
    "$id" : <document _id>, 
    "$db" : <database> 
}

For the users familiar with RDBMS concepts, it may look similar to foreign keys and joins, but MongoDB does not support joins: to resolve the reference, the additional query (or queries) should be executed. Nevertheless, it is quite a useful concept to commonly represent links between documents. Looking back to our Book example, let us assume the authors are stored in separate collection and every book is going to have a reference to its author. Here is an example of Author document:

{
    "_id": ObjectId("536a60ef0ad33fcab3abfc0f"),
    "firstName": "Kyle", 
    "lastName": "Banker"
}

And every Book now references the Author by its _id field and DBRef type:

{
    "_id": ObjectId("536a5fe20ad33fcab3abfc0e"),
    "title": "MongoDB In Action",
    "author": DBRef( "authors", "536a60ef0ad33fcab3abfc0f" ),
    "isbn": "978-1935182870",
    "published": new Date("Dec 16, 2011" ),
    "categories": [ "NoSQL", "Document Databases" ]
}

Later in this section we will see more examples of inserting different documents and using document references.

The one hard limit to keep in mind is that the maximum size of the document (represented in BSON format) is 16 megabytes. For more comprehensive overview of document data model, please refer to official documentation.

Command insert
Parameters
{
  insert: <collection>,
  documents: [ <document>, <document>, <document>, ... ],
  ordered: <true|false>,
  writeConcern: { <write concern> }
}
Wrapper db.<collection>.insert(<document or array of documents>, { writeConcern: { … }, ordered: <true|false> })

db.<collection>.save(<document>, writeConcern: { … })

Description Inserts one or more documents into collection <collection> and returns a document containing the status of all inserts.
Example In MongoDB shell, let us issue the command:

db.books.insert( {
  "title": "MongoDB In Action",
  "author": { "firstName": "Kyle", "lastName": "Banker" },
  "isbn": "978-1935182870",
  "published": new Date("Dec 16, 2011" ),
  "categories": [ "NoSQL", "Document Databases" ]
} )

02.DB.COLLECTION.INSERT

Alternatively, let us run the same command using runCommand() call:

db.runCommand( { 
  insert: 'books',
  documents: [
      {
        "title": "MongoDB In Action",
        "author": { "firstName": "Kyle", "lastName": "Banker" },
        "isbn": "978-1935182870",
        "published": new Date("Dec 16, 2011" ),
        "categories": [ "NoSQL", "Document Databases" ]
      }
  ]
} )

Considering an example with reference from Book to its Author, let us issue the following commands in MongoDB shell:

db.authors.insert( {
    "_id": "kyle-banker", 
    "firstName": "Kyle", 
    "lastName": "Banker"
} )
db.books.insert( {
    "title": "MongoDB In Action",
    "author": { "$ref": "authors", "$id": "kyle-banker" },
    "isbn": "978-1935182870",
    "published": new Date("Dec 16, 2011" ),
    "categories": [ "NoSQL", "Document Databases" ]
} )

02.DB.COLLECTION.INSERT.DBREF

Reference http://docs.mongodb.org/manual/reference/command/insert/

http://docs.mongodb.org/manual/reference/method/db.collection.insert/

http://docs.mongodb.org/manual/reference/method/db.collection.save/

insert

The write/update commands have a notion of write concern: the guarantee that MongoDB provides when reporting on the success of a write operation. The strength of the write concerns determines the level of guarantee. When inserts, updates and deletes have a weak write concern, write operations return quickly. Consequently, with strong write concerns the clients may await the MongoDB server instance(s) to confirm the write operations. In some failure cases, write operations issued with weak write concerns may not be persisted. We are going to get back to write concern in Part 5. MongoDB Replication Guide but if you would like to get more details right now, please refer to official documentation.

Command update
Parameters
{
  update: <collection>,
  updates: [
    { q: <query>, u: <update>, upsert: <true|false>, 
multi: <true|false> },
    { q: <query>, u: <update>, upsert: <true|false>, 
multi: <true|false> },
    { q: <query>, u: <update>, upsert: <true|false>, 
multi: <true|false> },
    ...
  ],
  ordered: <true|false>,
  writeConcern: { <write concern> }
}
Wrapper db.<collection>.update(<query>, <update>, { upsert: <true|false>, multi: <true|false>, writeConcern: { … } })

db.<collection>.save(<document>, writeConcern: { … })

Description Modifies an existing document or documents in a collection <collection> or inserts a new one if no documents match the query and the parameter upsert is set to true. The command can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update.

By default, the command updates a single document unless the parameter multi is to true andthen an update of all documents that match the query criteria will be performed.

The query syntax will be discussed in details in Queries section.

Example In MongoDB shell, let us issue the command (the original document will be replaced if exists):

db.books.update(
    { "title": "MongoDB In Action" }, 
    {
        "rating": 5,
        "categories": [ "NoSQL", "Document Databases",  "MongoDB" ]
    },
    { upsert: true }
)

02.DB.COLLECTION.UPDATE

Because we have executed the upsert, the result of the execution hints us that no matches have been found and a new document has been inserted.

Alternatively, let us run the same command using runCommand() call:

db.runCommand( {
  "update": "books", 
  "updates": [ 
    {
      "q": { "title": "MongoDB In Action" }, 
      "u": {
        "rating": 5,
        "categories": [ "NoSQL", "Document Databases",  "MongoDB" ]
      },
      upsert: true
    }
  ]
} )
Reference http://docs.mongodb.org/manual/reference/command/update/

http://docs.mongodb.org/manual/reference/method/db.collection.update/

http://docs.mongodb.org/manual/reference/method/db.collection.save/

update

The update command supports variety of operators to control the modification semantics which are listed in the table below (for more details please refer to official documentation):

Operator Description
$inc Increments the value of the field by the specified amount.
$mul Multiplies the value of the field by the specified amount.
$rename Renames a field.
$setOnInsert Sets the value of a field upon document creation during an upsert. Has no effect on update operations that modify existing documents.
$set Sets the value of a field in an existing document.
$unset Removes the specified field from an existing document.
$min Only updates if the existing field value is less than the specified value.
$max Only updates if the existing field value is greater than the specified value.
$currentDate Sets the value of a field to current date, either as a Date or a Timestamp.
$ Acts as a placeholder to update the first element that matches the query condition in an update.
$addToSet Adds elements to an existing array only if they do not already exist in the set.
$pop Removes the first or last item of an array.
$pullAll Removes all matching values from an array.
$pull Removes all array elements that match a specified query.
$push Adds an item to an array.
$each Modifies the $push and $addToSet operators to append multiple items for array updates.
$slice Modifies the $push operator to limit the size of updated arrays.
$sort Modifies the $push operator to reorder documents stored in an array.
$position Modifies the $push operator to specify the position in the array to add elements.
$bit Performs bitwise AND, OR, and XOR updates of integer values.
$isolated Modifies behavior of multi-updates to improve the isolation of the operation.

update

 

Here is an example of the update using some of the operators from the table above:

db.books.update(
    { "title": "MongoDB In Action" }, 
    {
        "$inc": { "rating": 1 },
        "$addToSet": { "categories": "MongoDB" }
    }
)
Command delete
Parameters
{
    delete: <collection>,
    deletes: [
         { q : <query>, limit : <integer> },
         { q : <query>, limit : <integer> },
         { q : <query>, limit : <integer> },
         ...
   ],
   ordered: <true|false>,
   writeConcern: { <write concern> }
}
Wrapper db.<collection>.remove(<query>, { justOne: <true|false>, writeConcern: { … } })
Description Removes documents from a collection <collection>. A multiple delete specifications could be provided. The command cannot operate on capped collections.

 

The query syntax will be discussed in details in Queries section.

Example In MongoDB shell, let us issue the command:

db.books.remove(
    { "title": "MongoDB In Action" }, 
    { "justOne": true }
)

02.DB.COLLECTION.REMOVE

Alternatively, let us run the same command using runCommand() call:

db.runCommand( {
    "delete": "books", 
    "deletes": [ 
        {
            "q": { "title": "MongoDB In Action" }, 
            "limit": 1
        }
    ]
} )
Reference http://docs.mongodb.org/manual/reference/command/delete/

http://docs.mongodb.org/manual/reference/method/db.collection.remove/

delete

 

Command findAndModify
Parameters
{
    findAndModify: <collection>,
    query: <query>,
    sort: <sort>,
    remove: <true|false>,
    update: <update>,
    new: <true|false>,
    fields: <fields>,
    upsert: <true|false>,
}
Wrapper db.<collection>. findAndModify ({ query: <query>, sort: <sort>, remove: <true|false>, update: <update>, new: <true|false>, fields: <fields>, upsert: <true|false> })
Description Finds, modifies and returns a single document in a collection <collection>. By default, the returned document does not include the modifications made by the update. To return the document with the modifications made, the new option should be set to true. If query selects multiple documents, the sort parameter determines which document should be modified.
Example In MongoDB shell, let us issue the commands (please notice that the original document will be replaced with updated one):

db.books.insert( {
    "title": "MongoDB In Action",
    "author": { firstName: "Kyle", lastName: "Banker" },
    "isbn": "978-1935182870",
    "published": new Date("Dec 16, 2011" ),
    "categories": [ "NoSQL", "Document Databases" ]
} )

db.books.findAndModify( {
    "query": { "title": "MongoDB In Action" }, 
    "remove": false,
    "new": true,
    "update": {
        "rating": 5,
        "categories": [ "NoSQL", "Document Databases",  "MongoDB" ]
    }
} )

02.DB.COLLECTION.FINDANDMODIFY

Alternatively, let us run the same command using runCommand() call:

db.runCommand( {
    "findAndModify": "books", 
    "query": { "title": "MongoDB In Action" },
    "update": {
        "rating": 5,
        "categories": [ "NoSQL", "Document Databases",  "MongoDB" ]
    },
    "remove": false,
    "new": true
} )
Reference http://docs.mongodb.org/manual/reference/command/findAndModify/

http://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/

findAndModify

 

The latest MongoDB release introduces the bulk operations support, which along with indexing will be covered in Part 7. MongoDB Security, Profiling, Indexing, Cursors and Bulk Operations Guide.

6. Queries

Queries are being used to retrieve data stored in the MongoDB database. In MongoDB, queries select documents from a single collection only (as we already know, joins are not supported). Queries specify the criteria to match the documents against. A query may include a projection to select the fields from the matching documents to return (quite useful to limit the amount of data that should be sent over the network).

Command db.<collection>.find(<criteria>, <projection>)
Description Selects documents in a collection <collection> and returns a cursor to the selected documents. Cursors will be covered in Part 7. MongoDB Security, Profiling, Indexing, Cursors and Bulk Operations Guide.

 

MongoDB supports a rich set of query operators (for more details please refer to official documentation):

  • $gt
  • $gte
  • $in
  • $lt
  • $lte
  • $ne
  • $nin
  • $or
  • $and
  • $not
  • $nor
  • $exists
  • $type
  • $mod
  • $regex
  • $text
  • $where
  • $geoWithin
  • $geoIntersects
  • $near
  • $nearSphere
  • $all
  • $elemMatch
  • $size
  • $elemMatch
  • $meta
  • $slice

 

The <projection> parameter specifies which fields of the document should be selected and returned to the clients:

{ 
    field1: <true|false>, 
    field2: <true|false> 
    ...
}
Example In MongoDB shell, let us issue the commands:

  • db.books.insert( { “title”: “MongoDB In Action” } )
  • db.books.insert( { “title”: “MongoDB. The Definitive Guide” } )
  • db.books.find( { “title”: { “$regex”: “MongoDB*” } } )

02.DB.COLLECTION.FIND

Reference http://docs.mongodb.org/manual/reference/method/db.collection.find/

db.find

 

Command db.<collection>.findOne(<criteria>, <projection>)
Description Returns only one document from the collection <collection> that satisfies the specified query criteria. If multiple documents match the query, this method returns the first document according to the natural order which reflects the order of documents on the disk. In capped collections, natural order is the same as insertion order. This command is very similar to db.<collection>.find(<criteria>, <projection>) described abovebut limits the result to at most one document.
Example In MongoDB shell, let us issue the commands:

  • db.books.insert( { “title”: “MongoDB In Action”, “price”: 10 } )
  • db.books.insert( { “title”: “MongoDB. The Definitive Guide”, “price”: 15 } )
  • db.books.findOne( { “price”: { “$gt”: 10 } }, { “title”: 1, “_id”: 0 } )

02.DB.COLLECTION.FINDONE

Reference http://docs.mongodb.org/manual/reference/method/db.collection.findOne/

db.findOne

 

With latest release MongoDB allows to limit the query processing time using maxTimeMS option (milliseconds). Please notice that maxTimeMS only accounts for CPU time and does not include network latency or idle time.

db.books.find( { “title”: { “$regex”: “MongoDB” } } ).maxTimeMS( 500 )

Command geoNear
Parameters
{
    geoNear: <collection>,
    near: <point>,
    limit: <limit>,
    num: <num>,
    maxDistance: <distance>,
    query: <query>,
    spherical: <true|false>,
    distanceMultiplier: <multiplier>,
    includeLocs: <true|false>,
    uniqueDocs: <true|false>
}
Description Specifies a point for which a geospatial query returns the closest documents from <collection> first. The query returns the documents from nearest to farthest. It is an alternative to the $near query operator. We are going to cover Geo indexes in details in Part 7. MongoDB Security, Profiling, Indexing, Cursors and Bulk Operations Guide.
Example In MongoDB shell, let us issue the commands:

db.stores.insert( { "name": "BestBuy", "location": [ 10, 15 ] } )
db.stores.ensureIndex( { "location": "2d" } )
db.runCommand( { 
    "geoNear": "stores",
    "near": [ 10, 14 ],
    "maxDistance": 6
} ) 	

02.DB.GEONEAR

Reference http://docs.mongodb.org/manual/reference/command/geoNear/

geoNear

 

Command geoSearch
Parameters
{ 
    geoSearch : <collection>,
    near: <point>, 
    maxDistance: <distance>,
    search: <query>, 
    limit: <limit> 
}
Description Returns the documents from collection <collection> based on location coordinates after collecting results based on some other query.
Example In MongoDB shell, let us issue the commands:

db.stores.insert( { "name": "BestBuy", "location": [ 10, 15 ] } )
db.stores.ensureIndex( 
    { "location": "geoHaystack", "name": 1 }, 
    { "bucketSize": 1 } 
)
db.runCommand( { 
    "geoSearch": "stores",
    "near": [ 10, 14 ],
    "maxDistance": 6,
    "search": { "name": "BestBuy" }
} ) 

02.DB.GEOSEARCH

Reference http://docs.mongodb.org/manual/reference/command/geoSearch/

geoSearch

 

In Part 7. MongoDB Security, Profiling, Indexing, Cursors and Bulk Operations Guide we will go through some advanced topics related to cursors, query profiling and query plans.

7. Aggregations

MongoDB provides a family of commands to perform collection-wide aggregation operations (so called aggregation framework). Most the commands we are going to cover in this section except mapReduce, which will be covered in Part 6. MongoDB Map Reduce Tutorial.

Command count
Parameters
{ 
    count: <collection>, 
    query: <query>, 
    limit: <limit>, 
    skip: <skip>, 
    hint: <hint> 
}
Wrapper db.<collection>.count(<query>)
Description Counts the number of documents in a collection <collection>. The query syntax is discussed in details in Queries section.
Example In MongoDB shell, let us issue the command: db.mycoll.count()

02.DB.COLLECTION.COUNT

Alternatively, let us run the same command using runCommand() call: db.runCommand( {

“count”: “mycoll” } )

Reference http://docs.mongodb.org/manual/reference/command/count/

http://docs.mongodb.org/manual/reference/method/db.collection.count/

count

 

Command distinct
Parameters
{ 
    distinct: <collection>, 
    key: <field>, 
    query: <query> 
}
Wrapper db.collection.distinct(<field>, <query>)
Description Finds the distinct values for a specified key <field> across a single collection <collection>. The query syntax is discussed in details in Queries section.
Example In MongoDB shell, let us issue the commands:

db.books.insert( { "title": "MongoDB In Action" } )
db.books.insert( { "title": "MongoDB. The Definitive Guide" } )
db.books.distinct("title" )

02.DB.COLLECTION.DISTINCT

Alternatively, let us run the same command using runCommand() call: db.runCommand( {

“distinct“: “books”, key“: “title” } )

Reference http://docs.mongodb.org/manual/reference/command/distinct/

http://docs.mongodb.org/manual/reference/method/db.collection.distinct/

distinct

 

Command group
Parameters
{
    group:
    {
         ns: <namespace>,
         key: <key>,
         $reduce: <reduce function>,
         Initial: <initial>,   
         $keyf: <key function>,
         cond: <query>,
         finalize: <finalize function>
   }
}
Wrapper db.collection.group({ key: <key>, reduce: <reduce function>, initial: <initial>, keyf: <key function>, cond: <query>, finalize: <finalize function> })
Description Groups documents in a collection <collection> by the specified key <field> and performs simple aggregation functions, such as computing counts and sums. For the users familiar with RDBMS concepts, this command is analogous to a SELECT <…> GROUP BY <…> statement in SQL. The query syntax is discussed in details in Queries section.
Example In MongoDB shell, let us issue the commands:

db.books.insert( { "title": "MongoDB In Action" } )
db.books.insert( { "title": "MongoDB. The Definitive Guide" } )
db.books.group( 
{ 
    "key": "title", 
    "reduce": function ( curr, result ) { result.total += 1 }, 
    "initial": { "total": 0 } 
} )

02.DB.COLLECTION.GROUP

Alternatively, let us run the same command using runCommand() call:

db.runCommand( { 
    "group": { 
        "ns": "books", 
        "key": "title", 
        "$reduce": function ( curr, result ) { result.total += 1 }, 
        "initial": { "total": 0 } 
    } 
} )
Reference http://docs.mongodb.org/manual/reference/command/group/

http://docs.mongodb.org/manual/reference/method/db.collection.group/

group

 

Command aggregate
Parameters
{
    aggregate: <collection>,
    pipeline: [ <stage>, <...> ],
    explain: <true|false>,
    allowDiskUse: <true|false>,
    cursor: <cursor>
}
Wrapper db.collection.aggregate(<pipeline>, { explain: <true|false>, allowDiskUse: <true|false>, cursor: <cursor> } )
Description Performs aggregation operation using the aggregation pipeline <pipeline>: processing the data from a collection <collection> with a sequence of stage-based manipulations (for more details please refer to official documentation).

 

The pipeline aggregation operators include:

  • $project
  • $match
  • $redact
  • $limit
  • $skip
  • $unwind
  • $group
  • $sort
  • $geoNear
  • $out

Each pipeline operator also supports the expression operators to calculate values within the pipeline (for more details please refer to official documentation).

Example In MongoDB shell, let us issue the commands:

db.books.insert( { "title": "MongoDB In Action", "price": 10 } )
db.books.insert( { "title": "MongoDB. The Definitive Guide", 
"price": 15 } )
db.books.aggregate( [  
{ "$match": { "title":  { "$regex": "MongoDB*" } } },  
{ "$group": { "_id": "mongodb", "total": { "$sum": "$price" } } },  
{ "$sort": { "total": -1 } } 
])

02.DB.COLLECTION.AGGREGATE

Alternatively, let us run the same command using runCommand() call:

db.runCommand( { 
"aggregate":  "books",     
"pipeline": [
  { "$match": { "title":  { "$regex": "MongoDB*" } } },  
  { "$group": { "_id": "mongodb", "total": { "$sum": "$price" } } },
  { "$sort": { "total": -1 } } 
] 
})
Reference http://docs.mongodb.org/manual/reference/command/aggregate/

http://docs.mongodb.org/manual/reference/method/db.collection.aggregate/

aggregate

8. GridFS

GridFS allows storing and retrieving files that exceed the MongoDB document size limit of 16MB (see please Documents section). Instead of storing a file in a single document, GridFS divides a file into parts (or chunks) and stores each of those chunks as a separate document. By default, the size of the chunk is 255KB. GridFS stores files in two collections (the fs prefix may be changed):

  • fs.chunks: stores file content as binary chunks
  • fs.files: stores file metadata

For more details, please refer to official documentation.

Command filemd5
Parameters
{ 
    filemd5: <object id>, 
    root: <root> 
}
Description Returns the MD5 hashes for a single file stored using the GridFS specification.
Example In the shell, let us run the command: bin/mongofiles put bin/mongofiles

gridfs1

In MongoDB shell, let us issue the command:

db.runCommand( { 
    "filemd5": ObjectId('536bbb3ffa052c2b649d2ee3'), 
    "root": "fs" 
} )

gridfs2

Reference http://docs.mongodb.org/manual/reference/command/filemd5/

filemd5

 

8. Server

MongoDB server supports a vast variety of commands to inspect its internals and monitor current activities. To satisfy the needs of enterprise deployments, MongoDB has a powerful, role-based security model to ensure that users and applications have access to only the data they are allowed to. Being a large topic, it will be covered in Part 7. MongoDB Security, Profiling, Indexing, Cursors and Bulk Operations Guide.

Command eval
Parameters
{
    eval: <function>,
    args: [ <arg1>, <arg2> ... ],
    nolock: <true|false>
}
Wrapper db.eval(<function>, <arguments>)
Description Provides the ability to evaluate JavaScript functions on the MongoDB server.
Example In MongoDB shell, let us issue the command:

db.eval( 
    function(title) {
        return db.books.insert( { "title": title } ).nInserted == 1;
    }, 
    "MongoDB in Action" 
)

02.DB.EVAL

Alternatively, let us run the same command using runCommand() call:

db.runCommand( {
   "eval":  function(title) {
        return db.books.insert( { "title": title } ).nInserted == 1;
    }, 
    "args": [ "MongoDB in Action" ]
} )
Reference http://docs.mongodb.org/manual/reference/command/eval/

http://docs.mongodb.org/manual/reference/method/db.eval/

eval

 

Command db.version()
Description Returns the version of the MongoDB server instance.
Example In MongoDB shell, let us issue the command: db.version()

02.DB.VERSION

Reference http://docs.mongodb.org/manual/reference/method/db.version/

db.version()

 

Command db.getMongo()
Description Returns the current database connection.
Example In MongoDB shell, let us issue the command: db.getMongo()

02.DB.GETMONGO

Reference http://docs.mongodb.org/manual/reference/method/db.getMongo/

db.getMongo()

 

Command db.currentOp()
Description Reports the current in-progress operations for the MongoDB database instance
Example In MongoDB shell, let us issue the command: db.currentOp()

02.DB.CURRENTOP

Reference http://docs.mongodb.org/manual/reference/method/db.currentOp/

db.currentOp()

 

Command db.killOp(<opid>)
Description Terminates an operation as specified by the operation ID (returned by db.currentOp()). The recommendation for this command is to use it to terminate the operations initiated by clients only and do not terminate internal database operations.
Reference http://docs.mongodb.org/manual/reference/method/db.killOp/

db.killOp()

 

Command buildInfo
Wrapper db.serverBuildInfo()
Description Returns a build summary for the current MongoDB server instance.
Example In MongoDB shell, let us issue the command: db.serverBuildInfo()

02.DB.SERVERBUILDINFO

Alternatively, let us run the same command using runCommand() call: db.runCommand( { buildInfo: 1 } )

 

Note: Only a fragment of the output is shown.

Reference http://docs.mongodb.org/manual/reference/command/buildInfo/

http://docs.mongodb.org/manual/reference/method/db.serverBuildInfo/

buildInfo

 

Command hostInfo
Wrapper db.hostInfo()
Description Returns information about the underlying system that MongoDB server instance is running on. Some of the returned fields are only included on some platforms.
Example In MongoDB shell, let us issue the command: db.hostInfo()

02.DB.HOSTINFO

Alternatively, let us run the same command using runCommand() call: db.runCommand( { hostInfo: 1 } )

Note: Only a fragment of the output is shown.

Reference http://docs.mongodb.org/manual/reference/command/hostInfo/

http://docs.mongodb.org/manual/reference/method/db.hostInfo/

hostInfo

 

Command serverStatus
Wrapper db.serverStatus()
Description Returns the overview of the MongoDB server instance process state, including different collection statistics about the instance.
Example In MongoDB shell, let us issue the command: db.serverStatus()

02.DB.SERVERSTATUS

Alternatively, let us run the same command using runCommand() call: db.runCommand( { serverStatus: 1 } )

Note: Only a fragment of the output is shown.

Reference http://docs.mongodb.org/manual/reference/command/serverStatus/

http://docs.mongodb.org/manual/reference/method/db.serverStatus/

serverStatus

 

Command shutdown
Wrapper db.shutdownServer()
Description Cleans up all database resources and then terminates the current MongoDB server instance process. It should be run in context of admin database.
Example In MongoDB shell, let us issue the commands:

use admin
db.shutdownServer()

02.DB.SHUTDOWN

Alternatively, let us run the same command using runCommand() call: db.adminCommand( { shutdown: 1 } )

Please notice that you have to restart your MongoDB server instance when command finishes execution as it will be terminated and MongoDB shell will not be able to connect to it anymore.

Reference http://docs.mongodb.org/manual/reference/command/shutdown/

http://docs.mongodb.org/manual/reference/method/db.shutdownServer/

shutdown

 

Command getCmdLineOpts
Description Outputs the command line options used to start the current MongoDB server instance. It should be run in context of admin database.
Example In MongoDB shell, let us issue the command: db.adminCommand( { getCmdLineOpts: 1 } )

02.GETCMDLINEOPTS

Reference http://docs.mongodb.org/manual/reference/command/getCmdLineOpts/

getCmdLineOpts

 

Command top
Description Returns usage statistics for each collection and provides amount of time (in microseconds) spent and operation counts for the following event types:

  • total
  • readLock
  • writeLock
  • queries
  • getmore
  • insert
  • update
  • remove
  • commands

It should be run in context of admin database.

Example In MongoDB shell, let us issue the command: db.adminCommand( { top: 1 } )

02.TOP

Note: Only a fragment of the output is shown.

Reference http://docs.mongodb.org/manual/reference/command/top/

top

 

Command getLog
Parameters
{ 
    getLog: <log> 
}
Description Returns recent messages from the current MongoDB server instance process log. The <log> parameter could have one of the following values:

  • global: the combined output of all recent log entries
  • startupWarnings: outputs errors or warnings occurred during the server start
  • rs: outputs log entries related to replica set activity

It should be run in context of admin database.

Example In MongoDB shell, let us issue the command: db.adminCommand( { getLog: 1 } )

02.GETLOG

Note: Only a fragment of the output is shown.

Reference http://docs.mongodb.org/manual/reference/command/getLog/

getLog

 

Command touch
Parameters
{ 
    touch: <collection>, 
    data: <true|false>, 
    index: <true|false> 
}
Description Loads data from the data storage layer into memory. It can load the indexes, data (documents) or both data (documents) and indexes. Execution of this command ensures that a collection <collection>, and/or its indexes, is/are in memory before another operation begins. By loading the collection or indexes into memory, MongoDB server instance might be able to perform subsequent operations more efficiently.
Example In MongoDB shell, let us issue the commands:

db.createCollection( "mycoll" )
db.runCommand( { touch: "mycoll", index: true } )

02.TOUCH

Reference http://docs.mongodb.org/manual/reference/command/touch/

touch

 

Command logRotate
Description Allows rotating the MongoDB server instance logs to prevent a single log file from consuming too much disk space. It should be run in context of admin database.
Example In MongoDB shell, let us issue the command: db.adminCommand( { logRotate: 1 } )

02.LOGROTATE

Reference http://docs.mongodb.org/manual/reference/command/logRotate/

logRotate

 

Command setParameter
Parameters
{ 
    <option>: <value> 
}
Description Allows modifying MongoDB server instance options normally set on the command line. The <option> parameter may have one of the following values:

  • journalCommitInterval
  • logLevel
  • logUserIds
  • notablescan
  • quiet
  • replApplyBatchSize
  • replIndexPrefetch
  • syncdelay
  • traceExceptions
  • textSearchEnabled
  • sslMode
  • clusterAuthMode
  • userCacheInvalidationIntervalSecs

It should be run in context of admin database.

Example In MongoDB shell, let us issue the command: db.adminCommand( { setParameter: 1, “textSearchEnabled”: true } )

02.SETPARAMETER

Reference http://docs.mongodb.org/manual/reference/command/setParameter/

setParameter

 

Command getParameter
Parameters
{ 
    <option>: <value> 
}
Description Allows retrieving the value of MongoDB server instance options normally set on the command line. The <option> parameter follows the setParameter command specification. It should be run in context of admin database.
Example In MongoDB shell, let us issue the command: db.adminCommand( { getParameter: 1, “textSearchEnabled”: 1 } )

02.GETPARAMETER

Reference http://docs.mongodb.org/manual/reference/command/getParameter/

getParameter

 

9. What’s next

In this section we have played quite a lot with MongoDB shell and seen most of the MongoDB commands in action. In the next section we are going to learn how to integrate MongoDB in your Java applications.

Andrey Redko

Andriy is a well-grounded software developer with more then 12 years of practical experience using Java/EE, C#/.NET, C++, Groovy, Ruby, functional programming (Scala), databases (MySQL, PostgreSQL, Oracle) and NoSQL solutions (MongoDB, Redis).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button