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

Commanduse <database>
DescriptionSwitches current database to <database> and assigns shell variable db to the current database.
ExampleIn MongoDB shell, let us issue the command: use mydb
02.USE
Referencehttp://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

use <database>

 

Commandshow dbs

show databases

DescriptionOutputs a list of all databases on the server instance.
ExampleIn MongoDB shell, let us issue the command: show dbs (or show databases)
Referencehttp://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

show dbs
show databases

 

Commandshow collections
DescriptionOutputs a list of all collections for current database.
ExampleIn MongoDB shell, let us issue the commands:

  • use local
  • show collections

02.SHOW.COLLECTIONS

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

show collections

 

Commandshow users
DescriptionOutputs a list of users for current database with their roles and custom data (if any).
ExampleIn MongoDB shell, let us issue the command: show users 02.SHOW.USERS
Referencehttp://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

show users

 

Commandshow roles
DescriptionOutputs a list of all roles, both user-defined and built-in, for the current database.
ExampleIn MongoDB shell, let us issue the command: show roles 02.SHOW.ROLES

Note: Only a fragment of the output is shown.

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

show roles

 

Commandshow logs
DescriptionShows the accessible logger names.
ExampleIn MongoDB shell, let us issue the command: show logs 02.SHOW.LOGS
Referencehttp://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

show logs

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

show log [name]

 

Commandload(<filename>)
DescriptionLoads and executes a JavaScript file with name filename inside current MongoDB shell environment.
ExampleLet 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

Referencehttp://docs.mongodb.org/manual/reference/method/load/

load(<filename>)

 

Commandhelp
DescriptionShows quick help on shell commands.
ExampleIn MongoDB shell, let us issue the command: help 02.HELP
Referencehttp://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.

Commanddb.runCommand(<command>)
DescriptionProvides 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.
ExampleIn MongoDB shell, let us issue the command: db.runCommand( { buildInfo: 1 } )

02.DB.RUNCOMMAND

Referencehttp://docs.mongodb.org/manual/reference/method/db.runCommand/

db.runCommand(<command>)

 

Commandversion()
DescriptionReturns the current version of the MongoDB shell instance.
ExampleIn MongoDB shell, let us issue the command: version() 02.VERSION
Referencehttp://docs.mongodb.org/manual/reference/method/version/

version()

 

CommandgetHostName()

hostname()

DescriptionReturns the hostname of the system running the MongoDB shell.
ExampleIn MongoDB shell, let us issue the command: hostname() (or getHostName()) 02.HOSTNAME
Referencehttp://docs.mongodb.org/manual/reference/method/hostname/

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

getHostName()
hostname()

 

CommandgetMemInfo()
DescriptionReturns 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
ExampleIn MongoDB shell, let us issue the command: getMemInfo() 02.GETMEMINFO
Referencehttp://docs.mongodb.org/manual/reference/method/getMemInfo/

getMemInfo()

 

Commandquit()
DescriptionExits the current shell session.
Referencehttp://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.

Commanddb.help()
DescriptionShow help for database methods.
ExampleIn MongoDB shell, let us issue the command: db.help() 02.DB.HELP

Note: Only a fragment of the output is shown.

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

db.help()

 

Commanddb.commandHelp(<command>)
DescriptionDisplays the help information for particular command <command> with examples of usage and expecting parameters.
ExampleIn MongoDB shell, let us issue the command: db.commandHelp(‘filemd5’) 02.DB.COMMANDHELP
Referencehttp://docs.mongodb.org/manual/reference/method/db.commandHelp/

db.commandHelp(<command>)

 

Commanddb.getName()
DescriptionReturns the current database name.
ExampleIn MongoDB shell, let us issue the command: db.getName() 02.DB.GETNAME
Referencehttp://docs.mongodb.org/manual/reference/method/db.getName/

db.getName

 

Commanddb.getSiblingDB(<database>)
DescriptionReturns 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).
ExampleIn MongoDB shell, let us issue the command: db.getSiblingDB(‘admin’).getName() 02.DB.GETSIBLINGDB
Referencehttp://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> ).

CommandlistCommands
Wrapperdb.listCommands()
DescriptionDisplays a list of all database commands with examples of usage and expecting parameters. The commands which require administrative privileges are marked as adminOnly.
ExampleIn 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.
Referencehttp://docs.mongodb.org/manual/reference/command/listCommands/

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

listCommands

 

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

listDatabases

 

Commandcopydb
Parameters
{ 
    fromhost: <hostname>,
    fromdb: <database>,
    todb: <database>,
    slaveOk: <true|false>,
    username: <username>,
    nonce: <nonce>,
    key: <key> 
}
Wrapperdb.copyDatabase(<fromdb>, <todb>, <fromhost>, <username>, <password>)
DescriptionCopies 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.
ExampleIn 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.

Referencehttp://docs.mongodb.org/manual/reference/command/copydb/

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

copydb

 

CommanddropDatabase
Wrapperdb.dropDatabase()
DescriptionRemoves the current database.It should be run in context of admin database.
ExampleIn 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()

Referencehttp://docs.mongodb.org/manual/reference/command/dropDatabase/

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

dropDatabase

 

Commandclone
Wrapperdb.cloneDatabase( <hostname>[:<port>] )
DescriptionThis 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.
ExampleAssuming 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’ } )

Referencehttp://docs.mongodb.org/manual/reference/command/clone/

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

clone

 

CommandrepairDatabase
Parameters
{ 
    preserveClonedFilesOnFailure: <true|false>,
    backupOriginalFiles: <true|false> 
}
Wrapperdb.repairDatabase()
DescriptionChecks and repairs any errors and inconsistencies with the data storage of current database.
ExampleIn 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 } )

Referencehttp://docs.mongodb.org/manual/reference/command/repairDatabase/

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

repairDatabase

 

Commandfsync
Parameters
{ 
    async: <true|false>, 
    lock: <true|false> 
}
Wrapperdb.fsyncLock() / db.fsyncUnlock()
DescriptionFlushes 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.
ExampleIn 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()
Referencehttp://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

 

CommanddbStats
Parameters
{ 
    scale: <scale>
}
Wrapperdb.stats( <scale> )
DescriptionOutputs the storage statistics for a given database.
ExampleIn 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 } )

Referencehttp://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.

Commanddb.<collection>.help()
DescriptionShow help on collection methods. The <collection> can be the name of an existing collection or a non-existing collection.
ExampleIn 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()

 

Commanddb.getCollectionNames()
DescriptionReturns all collections in the current database.
ExampleIn MongoDB shell, let us issue the command: db.getCollectionNames()

02.DB.GETCOLLECTIONNAMES

Referencehttp://docs.mongodb.org/manual/reference/method/db.getCollectionNames/

db.getCollectionNames()

 

Commanddb.getCollection(<name>)
DescriptionReturns 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).
ExampleIn MongoDB shell, let us issue the command: db.getCollection( ‘system.indexes’ )

02.DB.GETCOLLECTION

Referencehttp://docs.mongodb.org/manual/reference/method/db.getCollection/

db.getCollection(<name>)

 

Commandcreate
Parameters
{ 
    create: <collection>,
    capped: <true|false>,
    autoIndexId: <true|false>,
    size: <max_size>,
    max: <max_documents>,
    flags: <0|1>
}
Wrapperdb.createCollection( <collection>, {capped: <true|false>, autoIndexId: <true|false>, size: <number>, max: <number>} )
DescriptionExplicitly creates a new collection <collection>.
ExampleIn 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.

Referencehttp://docs.mongodb.org/manual/reference/command/create/

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

create

 

Commanddrop
Parameters
{ 
    drop: <collection> 
}
Wrapperdb.<collection>.drop()
DescriptionRemoves the specified collection <collection> from the database.
ExampleIn 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’ } )

Referencehttp://docs.mongodb.org/manual/reference/command/drop/

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

drop

 

CommandrenameCollection
Parameters
{ 
    renameCollection: <source_namespace>, 
    to: <target_namespace>, 
    dropTarget: <true|false> 
}
Wrapperdb.<collection>. renameCollection(<target>, <dropTarget>)
DescriptionChanges the name of an existing collection <collection>.It should be run in context of admin database.
ExampleIn 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’ } )

Referencehttp://docs.mongodb.org/manual/reference/command/renameCollection/

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

renameCollection

 

Commandvalidate
Parameters
{
    validate: <collection>,
    full: <true|false>
}
Wrapperdb.<collection>.validate( <full> )
DescriptionChecks 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.
ExampleIn 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’ } )

Referencehttp://docs.mongodb.org/manual/reference/command/validate/

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

validate

 

CommandcloneCollection
Parameters
{ 
    cloneCollection: <namespace>, 
    from: <hostname>, 
    query: { <query> } 
}
Wrapperdb.cloneCollection(<from>, <collection>, <query>)
DescriptionCopies a collection <collection> from a remote host to the current host.
ExampleAssuming 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’ } )

Referencehttp://docs.mongodb.org/manual/reference/command/cloneCollection/

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

cloneCollection

 

CommandcloneCollectionAsCapped
Parameters
{ 
    cloneCollectionAsCapped: <existing collection>, 
    toCollection: <capped collection>, 
    size: <capped size> 
}
DescriptionCreates 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.
ExampleIn MongoDB shell, let us issue the commands:

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

02.DB.CLONECOLLECTIONASCAPPED

Referencehttp://docs.mongodb.org/manual/reference/command/cloneCollectionAsCapped/

cloneCollectionAsCapped

 

CommandconvertToCapped
Parameters
{
    convertToCapped: <collection>, 
    size: <capped size> 
}
DescriptionConverts an existing, non-capped collection <collection> to a capped collection within the same database.
ExampleIn MongoDB shell, let us issue the commands:

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

02.DB.CONVERTTOCAPPED

Referencehttp://docs.mongodb.org/manual/reference/command/convertToCapped/

convertToCapped

 

CommandcollStats
Parameters
{ 
    collStats: <collection>, 
    scale : <scale> 
}
Wrapper
db.<collection>.stats(<scale>)
db. <collection>.totalSize()
db. <collection>.dataSize()
db. <collection>.totalIndexSize()
db. <collection>.storageSize()
DescriptionReturns a variety of storage statistics for a given collection <collection>.
ExampleIn 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’ } )

Referencehttp://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()

 

CommandcreateIndexes
Parameters
{
    createIndexes: <collection>,
    indexes: [
        {
            key: {
                <key-value_pair>,
                <key-value_pair>,
                ...
            },
            name: <index_name>,
            <option1>,
            <option2>,
            ...
        },
        { ... },
        { ... }
    ]
}
Wrapperdb.<collection>. ensureIndex(<keys>, <options>)
DescriptionBuilds one or more indexes on a collection <collection>.
ExampleIn 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'
        }
    ]
} )
Referencehttp://docs.mongodb.org/manual/reference/command/createIndexes/

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

createIndexes

 

CommanddropIndexes
Parameters
{ 
    dropIndexes: <collection>, 
    index: <index> 
}
Wrapperdb.<collection>.dropIndexes()

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

DescriptionDrops one or all indexes from the collection <collection>. To drop all indexes, pass the ‘*’ as the <index> value.
ExampleIn 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: ‘*’ } )

Referencehttp://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

 

CommandreIndex
Parameters
{ 
    reIndex: <collection>
}
Wrapperdb.<collection>.reIndex()
DescriptionDrops 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.
ExampleIn 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’ } )

Referencehttp://docs.mongodb.org/manual/reference/command/reIndex/

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

reIndex

 

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

02.DB.COMPACT

Referencehttp://docs.mongodb.org/manual/reference/command/compact/

compact

 

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

02.DB.COLLMOD

Referencehttp://docs.mongodb.org/manual/reference/command/collMod/

collMod

 

Commanddb.<collection>.isCapped()
DescriptionReturns true if the collection <collection> is a capped collection, otherwise returns false.
ExampleIn MongoDB shell, let us issue the command: db.mycoll.isCapped()

02.DB.COLLECTION.ISCAPPED

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

db.isCapped

 

Commanddb.<collection>.copyTo(<newCollection>)
DescriptionCopies 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).
ExampleIn MongoDB shell, let us issue the commands:

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

02.DB.COLLECTION.COPYTO

Referencehttp://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.

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

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

DescriptionInserts one or more documents into collection <collection> and returns a document containing the status of all inserts.
ExampleIn 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

Referencehttp://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.

Commandupdate
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> }
}
Wrapperdb.<collection>.update(<query>, <update>, { upsert: <true|false>, multi: <true|false>, writeConcern: { … } })

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

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

ExampleIn 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
    }
  ]
} )
Referencehttp://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):

OperatorDescription
$incIncrements the value of the field by the specified amount.
$mulMultiplies the value of the field by the specified amount.
$renameRenames a field.
$setOnInsertSets the value of a field upon document creation during an upsert. Has no effect on update operations that modify existing documents.
$setSets the value of a field in an existing document.
$unsetRemoves the specified field from an existing document.
$minOnly updates if the existing field value is less than the specified value.
$maxOnly updates if the existing field value is greater than the specified value.
$currentDateSets 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.
$addToSetAdds elements to an existing array only if they do not already exist in the set.
$popRemoves the first or last item of an array.
$pullAllRemoves all matching values from an array.
$pullRemoves all array elements that match a specified query.
$pushAdds an item to an array.
$eachModifies the $push and $addToSet operators to append multiple items for array updates.
$sliceModifies the $push operator to limit the size of updated arrays.
$sortModifies the $push operator to reorder documents stored in an array.
$positionModifies the $push operator to specify the position in the array to add elements.
$bitPerforms bitwise AND, OR, and XOR updates of integer values.
$isolatedModifies 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" }
    }
)
Commanddelete
Parameters
{
    delete: <collection>,
    deletes: [
         { q : <query>, limit : <integer> },
         { q : <query>, limit : <integer> },
         { q : <query>, limit : <integer> },
         ...
   ],
   ordered: <true|false>,
   writeConcern: { <write concern> }
}
Wrapperdb.<collection>.remove(<query>, { justOne: <true|false>, writeConcern: { … } })
DescriptionRemoves 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.

ExampleIn 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
        }
    ]
} )
Referencehttp://docs.mongodb.org/manual/reference/command/delete/

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

delete

 

CommandfindAndModify
Parameters
{
    findAndModify: <collection>,
    query: <query>,
    sort: <sort>,
    remove: <true|false>,
    update: <update>,
    new: <true|false>,
    fields: <fields>,
    upsert: <true|false>,
}
Wrapperdb.<collection>. findAndModify ({ query: <query>, sort: <sort>, remove: <true|false>, update: <update>, new: <true|false>, fields: <fields>, upsert: <true|false> })
DescriptionFinds, 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.
ExampleIn 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
} )
Referencehttp://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).

Commanddb.<collection>.find(<criteria>, <projection>)
DescriptionSelects 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> 
    ...
}
ExampleIn 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

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

db.find

 

Commanddb.<collection>.findOne(<criteria>, <projection>)
DescriptionReturns 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.
ExampleIn 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

Referencehttp://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 )

CommandgeoNear
Parameters
{
    geoNear: <collection>,
    near: <point>,
    limit: <limit>,
    num: <num>,
    maxDistance: <distance>,
    query: <query>,
    spherical: <true|false>,
    distanceMultiplier: <multiplier>,
    includeLocs: <true|false>,
    uniqueDocs: <true|false>
}
DescriptionSpecifies 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.
ExampleIn 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

Referencehttp://docs.mongodb.org/manual/reference/command/geoNear/

geoNear

 

CommandgeoSearch
Parameters
{ 
    geoSearch : <collection>,
    near: <point>, 
    maxDistance: <distance>,
    search: <query>, 
    limit: <limit> 
}
DescriptionReturns the documents from collection <collection> based on location coordinates after collecting results based on some other query.
ExampleIn 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

Referencehttp://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.

Commandcount
Parameters
{ 
    count: <collection>, 
    query: <query>, 
    limit: <limit>, 
    skip: <skip>, 
    hint: <hint> 
}
Wrapperdb.<collection>.count(<query>)
DescriptionCounts the number of documents in a collection <collection>. The query syntax is discussed in details in Queries section.
ExampleIn 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” } )

Referencehttp://docs.mongodb.org/manual/reference/command/count/

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

count

 

Commanddistinct
Parameters
{ 
    distinct: <collection>, 
    key: <field>, 
    query: <query> 
}
Wrapperdb.collection.distinct(<field>, <query>)
DescriptionFinds the distinct values for a specified key <field> across a single collection <collection>. The query syntax is discussed in details in Queries section.
ExampleIn 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” } )

Referencehttp://docs.mongodb.org/manual/reference/command/distinct/

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

distinct

 

Commandgroup
Parameters
{
    group:
    {
         ns: <namespace>,
         key: <key>,
         $reduce: <reduce function>,
         Initial: <initial>,   
         $keyf: <key function>,
         cond: <query>,
         finalize: <finalize function>
   }
}
Wrapperdb.collection.group({ key: <key>, reduce: <reduce function>, initial: <initial>, keyf: <key function>, cond: <query>, finalize: <finalize function> })
DescriptionGroups 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.
ExampleIn 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 } 
    } 
} )
Referencehttp://docs.mongodb.org/manual/reference/command/group/

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

group

 

Commandaggregate
Parameters
{
    aggregate: <collection>,
    pipeline: [ <stage>, <...> ],
    explain: <true|false>,
    allowDiskUse: <true|false>,
    cursor: <cursor>
}
Wrapperdb.collection.aggregate(<pipeline>, { explain: <true|false>, allowDiskUse: <true|false>, cursor: <cursor> } )
DescriptionPerforms 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).

ExampleIn 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 } } 
] 
})
Referencehttp://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.

Commandfilemd5
Parameters
{ 
    filemd5: <object id>, 
    root: <root> 
}
DescriptionReturns the MD5 hashes for a single file stored using the GridFS specification.
ExampleIn 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

Referencehttp://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.

Commandeval
Parameters
{
    eval: <function>,
    args: [ <arg1>, <arg2> ... ],
    nolock: <true|false>
}
Wrapperdb.eval(<function>, <arguments>)
DescriptionProvides the ability to evaluate JavaScript functions on the MongoDB server.
ExampleIn 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" ]
} )
Referencehttp://docs.mongodb.org/manual/reference/command/eval/

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

eval

 

Commanddb.version()
DescriptionReturns the version of the MongoDB server instance.
ExampleIn MongoDB shell, let us issue the command: db.version()

02.DB.VERSION

Referencehttp://docs.mongodb.org/manual/reference/method/db.version/

db.version()

 

Commanddb.getMongo()
DescriptionReturns the current database connection.
ExampleIn MongoDB shell, let us issue the command: db.getMongo()

02.DB.GETMONGO

Referencehttp://docs.mongodb.org/manual/reference/method/db.getMongo/

db.getMongo()

 

Commanddb.currentOp()
DescriptionReports the current in-progress operations for the MongoDB database instance
ExampleIn MongoDB shell, let us issue the command: db.currentOp()

02.DB.CURRENTOP

Referencehttp://docs.mongodb.org/manual/reference/method/db.currentOp/

db.currentOp()

 

Commanddb.killOp(<opid>)
DescriptionTerminates 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.
Referencehttp://docs.mongodb.org/manual/reference/method/db.killOp/

db.killOp()

 

CommandbuildInfo
Wrapperdb.serverBuildInfo()
DescriptionReturns a build summary for the current MongoDB server instance.
ExampleIn 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.

Referencehttp://docs.mongodb.org/manual/reference/command/buildInfo/

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

buildInfo

 

CommandhostInfo
Wrapperdb.hostInfo()
DescriptionReturns information about the underlying system that MongoDB server instance is running on. Some of the returned fields are only included on some platforms.
ExampleIn 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.

Referencehttp://docs.mongodb.org/manual/reference/command/hostInfo/

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

hostInfo

 

CommandserverStatus
Wrapperdb.serverStatus()
DescriptionReturns the overview of the MongoDB server instance process state, including different collection statistics about the instance.
ExampleIn 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.

Referencehttp://docs.mongodb.org/manual/reference/command/serverStatus/

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

serverStatus

 

Commandshutdown
Wrapperdb.shutdownServer()
DescriptionCleans up all database resources and then terminates the current MongoDB server instance process. It should be run in context of admin database.
ExampleIn 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.

Referencehttp://docs.mongodb.org/manual/reference/command/shutdown/

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

shutdown

 

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

02.GETCMDLINEOPTS

Referencehttp://docs.mongodb.org/manual/reference/command/getCmdLineOpts/

getCmdLineOpts

 

Commandtop
DescriptionReturns 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.

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

02.TOP

Note: Only a fragment of the output is shown.

Referencehttp://docs.mongodb.org/manual/reference/command/top/

top

 

CommandgetLog
Parameters
{ 
    getLog: <log> 
}
DescriptionReturns 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.

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

02.GETLOG

Note: Only a fragment of the output is shown.

Referencehttp://docs.mongodb.org/manual/reference/command/getLog/

getLog

 

Commandtouch
Parameters
{ 
    touch: <collection>, 
    data: <true|false>, 
    index: <true|false> 
}
DescriptionLoads 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.
ExampleIn MongoDB shell, let us issue the commands:

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

02.TOUCH

Referencehttp://docs.mongodb.org/manual/reference/command/touch/

touch

 

CommandlogRotate
DescriptionAllows 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.
ExampleIn MongoDB shell, let us issue the command: db.adminCommand( { logRotate: 1 } )

02.LOGROTATE

Referencehttp://docs.mongodb.org/manual/reference/command/logRotate/

logRotate

 

CommandsetParameter
Parameters
{ 
    <option>: <value> 
}
DescriptionAllows 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.

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

02.SETPARAMETER

Referencehttp://docs.mongodb.org/manual/reference/command/setParameter/

setParameter

 

CommandgetParameter
Parameters
{ 
    <option>: <value> 
}
DescriptionAllows 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.
ExampleIn MongoDB shell, let us issue the command: db.adminCommand( { getParameter: 1, “textSearchEnabled”: 1 } )

02.GETPARAMETER

Referencehttp://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