mongodb shell_MongoDB Shell指南–操作和命令

mongodb shell

本文是我们学院课程中名为MongoDB –可伸缩NoSQL DB的一部分

在本课程中,您将被介绍到MongoDB。 您将学习如何安装它以及如何通过它的外壳进行操作。 此外,您还将学习如何通过Java以编程方式访问它以及如何将Map Reduce与其一起使用。 最后,将解释更高级的概念,例如分片和复制。 在这里查看

1.简介

MongoDB Shell是发现MongoDB功能并管理服务器部署,实例,数据库,集合和文档的每个方面的最佳工具。 它基于JavaScript语言,用于执行命令和查询。 如果您对JavaScript的了解很少或不了解,请不要担心:由于可以遵循一种常见的模式,因此您几乎可以轻松地理解每个示例。

JSON是一种用于管理文档的格式,它还用于指定命令和查询以及返回其结果。 这样的统一带来了很多好处,因为JSON本质上是简单的,对人类友好的并且易于理解。

在本部分的教程中,我们打算使用MongoDB的外壳程序通过MongoDB支持的大多数命令和查询,但与分片有关的命令和查询(将在第4部分中详细介绍)和复制(将涉及到复制)有关详细信息,请参阅第5部分 。 更高级的主题将在第7部分中介绍。MongoDB安全性,性能分析,索引编制,游标和批量操作指南

每个部分都专门针对MongoDB的特定方面:我们从Shell Command Helpers开始 ,然后查看DatabasesCollectionsDocuments ,移至Queries and Aggregations ,最后完成Server特定的命令。

MongoDB有许多内部命令和实验命令,在大多数情况下,我们将不介绍这些命令。 它们的用法仅限于您可能从未遇到过的非常特定的场景(否则它们的行为可能会不稳定)。

下一小节假定您的MongoDB服务器实例已在本地计算机上启动并运行,如第1部分中所述。MongoDB安装-如何安装MongoDB

2. Shell命令助手

MongoDB Shell提供了几个命令帮助程序,它们可以建立上下文并隐式填充Shell变量,包括:

  • db:当前数据库上下文变量
  • rs:副本集上下文变量
  • sh:分片上下文变量

在不提供命令行参数的情况下,默认情况下, MongoDB shell在端口27017和名称测试数据库(磁盘上可能实际不存在)上连接到本地MongoDB服务器实例和端口27017

命令 使用<数据库>
描述 将当前数据库切换到<数据库>并将外壳变量db分配给当前数据库。
MongoDB Shell中,让我们发出命令: use mydb
02.使用
参考 http://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

使用<数据库>

命令 显示数据库

显示数据库

描述 输出服务器实例上所有数据库的列表。
MongoDB Shell中,让我们发出命令: show dbs (或show database)
参考 http://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

显示数据库
显示数据库

命令 显示收藏
描述 输出当前数据库的所有集合的列表。
MongoDB Shell中,让我们发出命令:
  • 使用本地
  • 显示收藏

02.SHOW.COLLECTIONS

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

显示收藏

命令 显示用户
描述 输出当前数据库的用户列表及其角色和自定义数据(如果有)。
MongoDB Shell中,让我们发出命令: show users 02.SHOW.USERS
参考 http://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

显示用户

命令 显示角色
描述 输出当前数据库的所有角色的列表,包括用户定义角色和内置角色。
MongoDB Shell中,让我们发出命令: show role 02.SHOW.ROLES

注意:仅显示输出的一部分。

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

显示角色

命令 显示日志
描述 显示可访问的记录器名称。
MongoDB Shell中,让我们发出命令: show logs 02.SHOW.LOGS
参考 http://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

显示日志

命令 显示日志[名称]
描述 输出日志存储器的最后一段。 如果省略记录器名称,则默认使用全局记录器。
MongoDB Shell中,让我们发出命令: show log global 02.SHOW.LOG

显示日志[名称]

命令 加载(<文件名>)
描述 在当前的MongoDB Shell环境中加载并执行一个名为filenameJavaScript文件。
让我们准备一个示例db.js脚本,该脚本位于MongoDB安装文件夹中,该脚本仅列出所有可用数据库并在控制台上输出其名称:
result = db.getSiblingDB( 'admin' )
.runCommand( { listDatabases: 1 } );
for( index in result.databases ) {
    print( result.databases[ index ].name );
}

MongoDB Shell中,让我们发出命令: load('db.js')

02.加载

参考 http://docs.mongodb.org/manual/reference/method/load/

加载(<文件名>)

命令 救命
描述 显示有关shell命令的快速帮助。
MongoDB Shell中,让我们发出命令: help 02.帮助
参考 http://docs.mongodb.org/manual/reference/mongo-shell/#command-helpers

救命

使用MongoDB Shell,至少有两种方法可以运行命令:

  • 使用通用的db.runCommand()函数调用
  • 使用更方便的db。<command>db。<collection>。<command>包装函数调用

在大多数情况下,第二个选项更具可读性,这将成为以下各节中示例的选择。 在大多数情况下,两个选项将并排展示(如果适用),因此您将能够选择自己喜欢的方式来运行命令。 请注意,并非所有命令都具有MongoDB Shell包装器,因此,它们只能与db.runCommand()函数调用一起运行。

命令 db.runCommand(<命令>)
描述 提供帮助程序以运行指定的数据库命令。 这是发出数据库命令的首选方法,因为它在外壳程序和驱动程序之间提供了一致的接口。
MongoDB Shell中,让我们发出命令: db.runCommand({buildInfo:1})

02.DB.RUNCOMMAND

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

db.runCommand(<命令>)

命令 版()
描述 返回MongoDB Shell实例的当前版本。
MongoDB Shell中,让我们发出命令: version() 02.版本
参考 http://docs.mongodb.org/manual/reference/method/version/

版()

命令 getHostName()

主机名()

描述 返回运行MongoDB Shell的系统的主机名。
MongoDB Shell中,让我们发出命令: hostname() (或getHostName()02.主机名
参考 http://docs.mongodb.org/manual/reference/method/hostname/

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

getHostName()
主机名()

命令 getMemInfo()
描述 返回包含两个字段的文档,这些字段报告JavaScript MongoDB shell使用的内存量(以兆字节为单位):
  • 常驻 :当前存储在物理RAM中的内存子集
  • virtual :工作内存,通常同时位于磁盘和物理RAM中
MongoDB Shell中,让我们发出命令: getMemInfo() 02.GETMEMINFO
参考 http://docs.mongodb.org/manual/reference/method/getMemInfo/

getMemInfo()

命令 退出()
描述 退出当前的shell会话。
参考 http://docs.mongodb.org/manual/reference/method/quit/

退出()

3.数据库

数据库是MongoDB中的顶级数据容器,其中包含一个或多个文档集合。 MongoDB为每个数据库在磁盘上创建一个或多个物理文件,积极地预先分配数据文件以保留空间并避免文件系统碎片。

数据文件名遵循以下模式:第一个数据文件的名称为<数据库名称> .0,下一个数据文件的名称为<数据库名称> .1 ,依此类推。 第一预分配的文件的大小是64兆字节 ,第二个具有尺寸128兆字节 ,下一个256兆字节,等等,高达2千兆字节的最大尺寸(此时所有后续文件将是在大小为2千兆字节 ) 。 请记住,在将数据插入数据库之前, MongoDB不会永久创建数据库。

默认情况下, MongoDB还会创建日志文件,该日志文件在将写入操作应用于数据库之前将其存储在磁盘上。

命令 db.help()
描述 显示有关数据库方法的帮助。
MongoDB Shell中,让我们发出命令: db.help() 02.数据库帮助

注意:仅显示输出的一部分。

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

db.help()

命令 db.commandHelp(<命令>)
描述 显示特定命令<command>的帮助信息以及用法和预期参数的示例。
MongoDB Shell中,让我们发出命令: db.commandHelp('filemd5') 02.DB.COMMANDHELP
参考 http://docs.mongodb.org/manual/reference/method/db.commandHelp/

db.commandHelp(<命令>)

命令 db.getName()
描述 返回当前数据库名称。
MongoDB Shell中,让我们发出命令: db.getName() 02.DB.GETNAME
参考 http://docs.mongodb.org/manual/reference/method/db.getName/

db.getName

命令 db.getSiblingDB(<数据库>)
描述 返回另一个数据库,而不修改外壳程序环境中的db变量。 它可以用作use <database>帮助程序的替代方法(请参阅Shell Command Helpers )。
MongoDB Shell中,让我们发出命令: db.getSiblingDB('admin')。getName() 02.DB.GETSIBLINGDB
参考 http://docs.mongodb.org/manual/reference/method/db.getSiblingDB/

db.getSiblingDB(<数据库>)

每个MongoDB服务器实例都有自己的本地数据库,该数据库存储复制过程中使用的数据以及其他特定于实例的数据。 复制不会影响本地数据库:永远不会复制本地数据库中的集合( 第5部分。MongoDB复制指南讨论了有关复制的更多信息)。 此外,还有一个管理数据库–用户必须有权访问才能运行某些管理命令的特权数据库。

要在管理数据库的上下文中运行命令,可以使用以下选项:

  • use admin
    db.runCommand( <command> )

    请注意,当前数据库将切换为admin

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

    链式调用更为冗长,但是当前数据库将不会切换并且保持不变。

  • db.adminCommand( <command> )

    db.getSiblingDB('admin').runCommand(<command>)的快捷方式。

命令 listCommands
包装纸 db.listCommands()
描述 显示所有数据库命令的列表,以及用法和预期参数的示例。 需要管理特权的命令被标记为adminOnly
MongoDB Shell中,让我们发出命令: db.listCommands() 02.DB.LISTCOMMANDS
另外,让我们使用runCommand()调用运行同一命令: db.runCommand({listCommands:1}) 注意:仅显示输出的一部分。
参考 http://docs.mongodb.org/manual/reference/command/listCommands/

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

listCommands

命令 listDatabases
描述 此命令提供现有数据库的列表以及有关它们的基本统计信息。 它应在管理数据库的上下文中运行。
MongoDB Shell中,让我们发出命令: db.getSiblingDB('admin')。runCommand({listDatabases:1}) 02.DB.LISTDATABASES
参考 http://docs.mongodb.org/manual/reference/command/listDatabases/

listDatabases

命令 复制数据库
参量
{ 
    fromhost: <hostname>,
    fromdb: <database>,
    todb: <database>,
    slaveOk: <true|false>,
    username: <username>,
    nonce: <nonce>,
    key: <key> 
}
包装纸 db.copyDatabase(<fromdb>,<todb>,<fromhost>,<用户名>,<密码>)
描述 将数据库从远程主机复制到当前主机,或将数据库复制到当前主机内的另一个数据库。 它应在管理数据库的上下文中运行。
MongoDB Shell中,让我们发出命令:
db.getSiblingDB('admin').runCommand( { 
    copydb: 1, 
    fromdb: 'test', 
    todb: 'test2' 
} )

02.DB.COPYDB

另外,让我们使用MongoDB Shell包装器运行相同的命令: db.copyDatabase('test','test2')

02.DB.COPYDATABASE
每次运行命令后,连续运行show dbs将在列表中输出新数据库test2

参考 http://docs.mongodb.org/manual/reference/command/copydb/

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

复制数据库

命令 dropDatabase
包装纸 db.dropDatabase()
描述 删除当前数据库。它应在管理数据库的上下文中运行。
MongoDB Shell中,让我们发出命令:
    • 使用test2
    • db.dropDatabase()

02.DB.DROPDATABASE
另外,让我们使用runCommand()调用运行相同的命令:

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

甚至最短的版本: db.getSiblingDB('test2').dropDatabase()

参考 http://docs.mongodb.org/manual/reference/command/dropDatabase/

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

dropDatabase

命令 克隆
包装纸 db.cloneDatabase(<主机名> [:<端口>])
描述 此命令从运行在<主机名>端口<端口>上的远程MongoDB实例克隆与当前数据库同名的数据库到当前主机。
假设在另一个运行在端口27018上的MongoDB服务器实例中,让我们在shell中发出命令: db.cloneDatabase('localhost:27018') 02.DB.CLONEDATABASE

另外,让我们使用runCommand()调用运行相同的命令: db.runCommand({clone:'localhost:27018'})

参考 http://docs.mongodb.org/manual/reference/command/clone/

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

克隆

命令 repairDatabase
参量
{ 
    preserveClonedFilesOnFailure: <true|false>,
    backupOriginalFiles: <true|false> 
}
包装纸 db.repairDatabase()
描述 检查并修复与当前数据库的数据存储中的任何错误和不一致。
MongoDB Shell中,让我们发出命令: db.repairDatabase()

02.DB.REPAIRDATABASE

另外,让我们使用runCommand()调用运行相同的命令: db.runCommand({repairDatabase:1})

参考 http://docs.mongodb.org/manual/reference/command/repairDatabase/

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

repairDatabase

命令 同步
参量
{ 
    async: <true|false>, 
    lock: <true|false> 
}
包装纸 db.fsyncLock()/ db.fsyncUnlock()
描述 将所有未决的写操作从存储层刷新到磁盘。 或者,它可以锁定服务器实例并阻止写操作以捕获备份,应在管理数据库的上下文中运行。
MongoDB Shell中,让我们发出命令:
  • db.fsyncLock()
  • db.fsyncUnlock()

02.DB.FSYNCLOCK

另外,让我们使用runCommand()调用运行相同的命令:

  • db.adminCommand({fsync:1,lock:true})
  • db.fsyncUnlock()
参考 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/

同步

命令 dbStats
参量
{ 
    scale: <scale>
}
包装纸 db.stats(<scale>)
描述 输出给定数据库的存储统计信息。
MongoDB Shell中,让我们发出命令: db.stats()

02.数据库统计

或者,让我们使用runCommand()调用运行相同的命令: db.runCommand({dbStats:1})

参考 http://docs.mongodb.org/manual/reference/command/dbStats/

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

dbStats

4.馆藏

集合是共享一个或多个索引的MongoDB文档的容器。 对于熟悉RDBMS概念的用户,集合相当于表。 集合属于单个数据库,并且不对包含文档执行任何架构。 对任何单个集合都可以包含的文档数量没有限制,除非它是一种特殊的集合,称为封顶集合:固定大小的集合,当其达到最大大小时会自动覆盖其最早的条目。

集合与数据库名称一起形成一个命名空间:使用句点'将数据库名称与集合名称连接在一起 '字符,例如:

  • test.collection1
  • test.collection1.subcollection1

除用户定义的集合外, MongoDB将系统信息存储在使用<database> .system。*名称空间并保留供内部使用的集合中。 管理员数据库(请参阅数据库部分)包括以下系统集合:

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

每个用户数据库都定义了以下系统集合:

  • <数据库> .system.namespaces
  • <数据库> .system.indexes
  • <数据库> .system.profile
  • <数据库> .system.js

在本节中,我们不会直接探索系统集合,但是如果您有兴趣获取更多详细信息,请参考官方文档

命令 db。<集合> .help()
描述 在收集方法上显示帮助。 <collection>可以是现有集合或不存在的集合的名称。
MongoDB Shell中,让我们发出命令: db.mycoll.help()

02.DB.COLLECTION.HELP

注意:仅显示输出的一部分。

db。<集合> .help()

命令 db.getCollectionNames()
描述 返回当前数据库中的所有集合。
MongoDB Shell中,让我们发出命令: db.getCollectionNames()

02.DB.GETCOLLECTIONNAMES

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

db.getCollectionNames()

命令 db.getCollection(<名称>)
描述 返回集合名称。 这对于名称可能与外壳本身交互的集合很有用(例如,以_开头或与内置数据库命令名称相同)。
MongoDB Shell中,让我们发出命令: db.getCollection('system.indexes')

02.DB.GETCOLLECTION

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

db.getCollection(<名称>)

命令 创造
参量
{ 
    create: <collection>,
    capped: <true|false>,
    autoIndexId: <true|false>,
    size: <max_size>,
    max: <max_documents>,
    flags: <0|1>
}
包装纸 db.createCollection(<collection>,{封顶:<true | false>,autoIndexId:<true | false>,大小:<number>,max:<number>}))
描述 显式创建一个新的集合<collection>
MongoDB Shell中,让我们发出命令: db.createCollection('mycoll',{capped:false})

02.DB.CREATECOLLECTION

另外,让我们使用runCommand()调用运行相同的命令: db.runCommand({create:'mycoll',capped:false})

db.getCollectionNames()的连续调用将输出新创建的集合。

参考 http://docs.mongodb.org/manual/reference/command/create/

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

创造

命令 下降
参量
{ 
    drop: <collection> 
}
包装纸 db。<集合> .drop()
描述 从数据库中删除指定的集合<collection>
MongoDB Shell中,让我们发出命令:
  • db.createCollection('mycoll')
  • db.mycoll.drop()

02.DB.COLLECTION.DROP

另外,让我们使用runCommand()调用运行相同的命令: db.runCommand({drop:'mycoll'})

参考 http://docs.mongodb.org/manual/reference/command/drop/

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

下降

命令 namedCollection
参量
{ 
    renameCollection: <source_namespace>, 
    to: <target_namespace>, 
    dropTarget: <true|false> 
}
包装纸 db。<集合>。 namedCollection(<target>,<dropTarget>)
描述 更改现有集合<集合>的名称。它应在管理数据库的上下文中运行。
MongoDB Shell中,让我们发出命令:
  • db.createCollection('mycoll')
  • db.mycoll.renameCollection('mycoll2')

02.DB.COLLECTION.RENAMECOLLECTION

另外,让我们使用runCommand()调用运行相同的命令: db.adminCommand({namedCollection:'test.mycoll',to:'test.mycoll2'})

参考 http://docs.mongodb.org/manual/reference/command/renameCollection/

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

namedCollection

命令 验证
参量
{
    validate: <collection>,
    full: <true|false>
}
包装纸 db。<collection> .validate(<full>)
描述 通过扫描集合的数据和索引来检查集合<collection>中的结构是否正确。 该命令返回有关集合的磁盘表示形式的信息。
MongoDB Shell中,让我们发出命令:
  • db.createCollection('mycoll')
  • db.mycoll.validate()

02.DB.COLLECTION.VALIDATE

另外,让我们使用runCommand()调用运行相同的命令: db.runCommand({validate:'mycoll'})

参考 http://docs.mongodb.org/manual/reference/command/validate/

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

验证

命令 cloneCollection
参量
{ 
    cloneCollection: <namespace>, 
    from: <hostname>, 
    query: { <query> } 
}
包装纸 db.cloneCollection(<来自>,<集合>,<查询>)
描述 将集合<collection>从远程主机复制到当前主机。
假设在另一个运行在端口27018上的MongoDB服务器实例中,让我们在外壳中发出命令: db.cloneCollection('localhost:27018','test.mycoll')

02.DB.CLONECOLLECTION

或者,让我们使用runCommand()调用运行相同的命令: db.runCommand({cloneCollection:'test.mycoll',来自:'localhost:27018'})

参考 http://docs.mongodb.org/manual/reference/command/cloneCollection/

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

cloneCollection

命令 cloneCollectionAsCapped
参量
{ 
    cloneCollectionAsCapped: <existing collection>, 
    toCollection: <capped collection>, 
    size: <capped size> 
}
描述 从同一个数据库中现有的<existing collection>的非上限集合中创建一个新的上限集合<capped collection> 。 该操作不会影响原始的非上限集合。
MongoDB Shell中,让我们发出命令:
db.createCollection( 'mycoll' )
db.runCommand( { 
    cloneCollectionAsCapped: 'mycoll', 
    toCollection: 'mycollcapped', 
    size: 10 
} )

02.DB.CLONECOLLECTIONASCAPPED

参考 http://docs.mongodb.org/manual/reference/command/cloneCollectionAsCapped/

cloneCollectionAsCapped

命令 convertToCapped
参量
{
    convertToCapped: <collection>, 
    size: <capped size> 
}
描述 将现有的无上限集合<collection>转换为同一数据库中的有上限集合。
MongoDB Shell中,让我们发出命令:
db.createCollection( 'mycoll' )
db.runCommand( { 
    convertToCapped: 'mycoll', 
    size: 10 
} )

02.数据库已转换

参考 http://docs.mongodb.org/manual/reference/command/convertToCapped/

convertToCapped

命令 collStats
参量
{ 
    collStats: <collection>, 
    scale : <scale> 
}
包装纸
db.<collection>.stats(<scale>)
db. <collection>.totalSize()
db. <collection>.dataSize()
db. <collection>.totalIndexSize()
db. <collection>.storageSize()
描述 返回给定集合<collection>的各种存储统计信息。
MongoDB Shell中,让我们发出命令: db.mycoll.stats()

02.DB.COLLECTION.STATS

另外,让我们使用runCommand()调用运行相同的命令: db.runCommand({collStats:'mycoll'})

参考 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()

命令 createIndexes
参量
{
    createIndexes: <collection>,
    indexes: [
        {
            key: {
                <key-value_pair>,
                <key-value_pair>,
                ...
            },
            name: <index_name>,
            <option1>,
            <option2>,
            ...
        },
        { ... },
        { ... }
    ]
}
包装纸 db。<集合>。 sureIndex(<键>,<选项>)
描述 在集合<collection>上构建一个或多个索引。
MongoDB Shell中,让我们发出命令: db.mycoll.ensureIndex({content:“ text”})

02.DB.COLLECTION.ENSUREINDEX

另外,让我们使用runCommand()调用运行相同的命令:

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

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

createIndexes

命令 dropIndexes
参量
{ 
    dropIndexes: <collection>, 
    index: <index> 
}
包装纸 db。<collection> .dropIndexes()

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

描述 从集合<collection>中删除一个或所有索引。 要删除所有索引,请将“ *”作为<index>值传递。
MongoDB Shell中,让我们发出命令:
db.mycoll.ensureIndex( { content: "text" } )
db.mycoll.dropIndexes()

02.DB.COLLECTION.DROPINDEXES

另外,让我们使用runCommand()调用运行相同的命令: db.runCommand({dropIndexes:'mycoll',index:'*'})

参考 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

命令 索引
参量
{ 
    reIndex: <collection>
}
包装纸 db。<collection> .reIndex()
描述 删除集合<collection>上的所有索引并重新创建它们。 对于具有大量数据和/或大量索引的集合,此操作可能会很昂贵。
MongoDB Shell中,让我们发出命令: db.mycoll.reIndex()

02.DB.COLLECTION.REINDEX

另外,让我们使用runCommand()调用运行相同的命令: db.runCommand({reIndex:'mycoll'})

参考 http://docs.mongodb.org/manual/reference/command/reIndex/

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

索引

命令 紧凑
参量
{ 
    compact: <collection>
}
描述 重写和整理集合<collection>中的所有数据以及对该集合上的所有索引进行碎片整理。
MongoDB Shell中,让我们发出命令: db.runCommand({compact:'mycoll'})

02.DB.COMPACT

参考 http://docs.mongodb.org/manual/reference/command/compact/

紧凑

命令 collMod
参量
{
    collMod: <collection> , 
    <flag> : <value> 
}
描述 可以将标志添加到集合<collection>中以修改其行为。
MongoDB Shell中,让我们发出命令:db.runCommand({collMod:'mycoll',usePowerOf2Sizes:true})

02.数据库

参考 http://docs.mongodb.org/manual/reference/command/collMod/

collMod

命令 db。<collection> .isCapped()
描述 如果集合<collection>是一个封闭的集合,则返回true,否则返回false。
MongoDB Shell中,让我们发出命令:db.mycoll.isCapped()

02.DB.COLLECTION.ISCAPPED

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

db.isCapped

命令 db。<集合> .copyTo(<newCollection>)
描述 使用服务器端JavaScript将所有文档从集合<collection>复制到新集合<newCollection>中 。 如果集合<newCollection>不存在,将创建它。 该命令返回复制的文档数(如果源集合为空,则返回0 )。
MongoDB Shell中,让我们发出命令
db.createCollection( 'mycoll' )
db.mycoll.copyTo( 'mycollcopy' )

02.DB.COLLECTION.COPYTO

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

db.copyTo

5.文件

MongoDB中 ,数据以JSON文档的形式表示和存储:字段和值对。 更准确地说, MongoDB使用二进制 JSON(BSON)将序列化的文档存储在磁盘上,但对于用户而言,它看起来像常规JSON (至少在MongoDB shell中)。 支持的归档数据类型的范围令人印象深刻(请参考BSON数据类型参考):

  • 目的
  • 数组
  • 二进制数据
  • 未定义
  • 对象编号
  • 布尔型
  • 日期
  • 空值
  • 正则表达式
  • JavaScript(有/无范围)
  • 32位整数
  • 64位整数
  • 时间戳记

还支持其他文档(所谓的嵌入式文档),数组,文档数组和引用。

字段名称有两个限制:

  • 名称为_id的字段保留用作主键,并且在整个集合中必须是唯一的(它是不可变的,并且可以是数组以外的任何类型)。 此字段始终是文档中的第一个字段。
  • 字段名称不能以美元符号“ $”开头,并且不能包含点“。”。 字符。 这些是保留的。

例如,代表一本书的简单文档可能如下所示:

{
    "_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" ]
}

引用( DBRef )是从一个文档到另一个文档的指针(使用文档的_id字段的值,集合名称以及(可选)其数据库名称):

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

对于熟悉RDBMS概念的用户,它看起来类似于外键和联接,但是MongoDB不支持联接:要解析引用,应执行一个或多个附加查询。 但是,通常表示文档之间的链接是一个非常有用的概念。 回到我们的Book示例,让我们假设作者存储在单独的集合中,并且每本书都会对其作者进行引用。 这是作者文档的示例:

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

现在,每本书都通过其_id字段和DBRef类型引用作者

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

在本节的后面,我们将看到更多插入不同文档和使用文档引用的示例。

要牢记的一个硬限制是文档的最大大小(以BSON格式表示)为16兆字节 。 有关文档数据模型的更全面概述,请参阅官方文档

命令
参量
{
  insert: <collection>,
  documents: [ <document>, <document>, <document>, ... ],
  ordered: <true|false>,
  writeConcern: { <write concern> }
}
包装纸 db。<collection> .insert(<文档或文档数组>,{writeConcern:{…},已排序:<true | false>})

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

描述 将一个或多个文档插入集合<collection>中,并返回包含所有插入状态的文档。
MongoDB Shell中,让我们发出命令
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

另外,让我们使用runCommand()调用运行相同的命令:

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" ]
      }
  ]
} )

考虑一个从BookAuthor的示例,让我们在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

参考 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/

write / update命令具有写关注点的概念: MongoDB在报告写操作成功时提供的保证。 写关注的强度决定了保证的水平。 当插入,更新和删除的写操作很弱时,写操作将Swift返回。 因此,由于存在强烈的写入问题,客户端可能会等待MongoDB服务器实例确认写入操作。 在某些故障情况下,可能不会坚持执行写操作较弱的写操作。 我们将在第5部分中写问题 。但是,如果您现在想获取更多详细信息,请参考官方文档

命令 更新
参量
{
  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> }
}
包装纸 db。<collection> .update(<query>,<update>,{upsert:<true | false>,multi:<true | false>,writeConcern:{…}})

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

描述 如果没有文档与查询匹配并且参数upsert设置为true,则修改集合<collection>中的一个或多个现有文档或插入一个新文档。 该命令可以修改一个或多个现有文档的特定字段,或完全替换现有文档,具体取决于更新。

默认情况下,该命令将更新单个文档,除非参数multitrue,然后将执行所有与查询条件匹配的文档的更新。

查询语法将在“ 查询”部分中详细讨论。

MongoDB Shell中,让我们发出命令(如果存在,将替换原始文档)
db.books.update(
    { "title": "MongoDB In Action" }, 
    {
        "rating": 5,
        "categories": [ "NoSQL", "Document Databases",  "MongoDB" ]
    },
    { upsert: true }
)

02.DB.COLLECTION.UPDATE

因为我们执行了upsert ,所以执行的结果提示我们未找到匹配项,并且已插入新文档。

另外,让我们使用runCommand()调用运行相同的命令:

db.runCommand( {
  "update": "books", 
  "updates": [ 
    {
      "q": { "title": "MongoDB In Action" }, 
      "u": {
        "rating": 5,
        "categories": [ "NoSQL", "Document Databases",  "MongoDB" ]
      },
      upsert: true
    }
  ]
} )
参考 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命令支持各种运算符来控制下表中列出的修改语义(有关更多详细信息,请参阅官方文档 ):

操作员 描述
$ inc 将字段的值增加指定的数量。
$ mul 将字段的值乘以指定的数量。
$重命名 重命名字段。
$ setOnInsert upsert过程中,在创建文档时设置字段的值。 对修改现有文档的更新操作没有影响。
$ set 设置现有文档中字段的值。
$未设定 从现有文档中删除指定的字段。
$ min 仅在现有字段值小于指定值时更新。
最高$ 仅在现有字段值大于指定值时更新。
$ currentDate 将字段的值设置为当前日期,即日期或时间戳。
$ 充当占位符,以在更新中更新与查询条件匹配的第一个元素。
$ addToSet 仅当元素不存在于集合中时才将它们添加到现有数组中。
流行音乐 删除数组的第一项或最后一项。
$ pullAll 从数组中删除所有匹配的值。
$拉 删除与指定查询匹配的所有数组元素。
$推 将项目添加到数组。
$每个 修改$ push$ addToSet运算符以附加多个项以进行数组更新。
$切片 修改$ push运算符以限制更新数组的大小。
$ sort 修改$ push运算符以对存储在数组中的文档重新排序。
$位置 修改$ push运算符,以指定要添加元素的数组中的位置。
$位 执行整数值的按位ANDORXOR更新。
$已隔离 修改多次更新的行为,以改善操作的隔离性。

更新

这是使用上表中的某些运算符进行更新的示例:

db.books.update(
    { "title": "MongoDB In Action" }, 
    {
        "$inc": { "rating": 1 },
        "$addToSet": { "categories": "MongoDB" }
    }
)
命令 删除
参量
{
    delete: <collection>,
    deletes: [
         { q : <query>, limit : <integer> },
         { q : <query>, limit : <integer> },
         { q : <query>, limit : <integer> },
         ...
   ],
   ordered: <true|false>,
   writeConcern: { <write concern> }
}
包装纸 db。<collection> .remove(<query>,{justOne:<true | false>,writeConcern:{…}})
描述 从集合<collection>中删除文档。 可以提供多个删除规范。 该命令无法对有上限的集合进行操作。

查询语法将在“ 查询”部分中详细讨论。

MongoDB Shell中,让我们发出命令
db.books.remove(
    { "title": "MongoDB In Action" }, 
    { "justOne": true }
)

02.DB.COLLECTION.REMOVE

另外,让我们使用runCommand()调用运行相同的命令:

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

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

删除

命令 findAndModify
参量
{
    findAndModify: <collection>,
    query: <query>,
    sort: <sort>,
    remove: <true|false>,
    update: <update>,
    new: <true|false>,
    fields: <fields>,
    upsert: <true|false>,
}
包装纸 db。<集合>。 findAndModify({查询:<查询>,排序:<排序>,删除:<true | false>,更新:<update>,新建:<true | false>,字段:<fields>,upsert:<true | false> })
描述 在集合<collection>中查找,修改和返回单个文档。 默认情况下,返回的文档不包含更新所做的修改。 要返回修改后的文档,应将new选项设置为true 。 如果查询选择了多个文档,则sort参数确定应修改哪个文档。
MongoDB Shell中,让我们发出命令(请注意,原始文档将被更新的文档替换):
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

另外,让我们使用runCommand()调用运行相同的命令:

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

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

findAndModify

最新的MongoDB版本引入了批量操作支持,并将在第7部分中介绍索引。MongoDB安全,性能分析,索引,游标和批量操作指南

6.查询

查询用于检索MongoDB数据库中存储的数据。 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).

命令 db.<collection>.find(<criteria>, <projection>)
描述 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> 
    ...
}
MongoDB Shell中,让我们发出命令:
  • 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

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

db.find

命令 db.<collection>.findOne(<criteria>, <projection>)
描述 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.
MongoDB Shell中,让我们发出命令:
  • 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

参考 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 )

命令 geoNear
参量
{
    geoNear: <collection>,
    near: <point>,
    limit: <limit>,
    num: <num>,
    maxDistance: <distance>,
    query: <query>,
    spherical: <true|false>,
    distanceMultiplier: <multiplier>,
    includeLocs: <true|false>,
    uniqueDocs: <true|false>
}
描述 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 .
MongoDB Shell中,让我们发出命令:
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

参考 http://docs.mongodb.org/manual/reference/command/geoNear/

geoNear

命令 geoSearch
参量
{ 
    geoSearch : <collection>,
    near: <point>, 
    maxDistance: <distance>,
    search: <query>, 
    limit: <limit> 
}
描述 Returns the documents from collection <collection> based on location coordinates after collecting results based on some other query.
MongoDB Shell中,让我们发出命令:
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

参考 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 .

命令 count
参量
{ 
    count: <collection>, 
    query: <query>, 
    limit: <limit>, 
    skip: <skip>, 
    hint: <hint> 
}
包装纸 db.<collection>.count(<query>)
描述 Counts the number of documents in a collection <collection> . The query syntax is discussed in details in Queries section.
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” } )

参考 http://docs.mongodb.org/manual/reference/command/count/

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

计数

命令 distinct
参量
{ 
    distinct: <collection>, 
    key: <field>, 
    query: <query> 
}
包装纸 db.collection.distinct(<field>, <query>)
描述 Finds the distinct values for a specified key <field> across a single collection <collection> . The query syntax is discussed in details in Queries section.
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” } )

参考 http://docs.mongodb.org/manual/reference/command/distinct/

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

不同

命令 group
参量
{
    group:
    {
         ns: <namespace>,
         key: <key>,
         $reduce: <reduce function>,
         Initial: <initial>,   
         $keyf: <key function>,
         cond: <query>,
         finalize: <finalize function>
   }
}
包装纸 db.collection.group({ key: <key>, reduce: <reduce function>, initial: <initial>, keyf: <key function>, cond: <query>, finalize: <finalize function> })
描述 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.
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 } 
    } 
} )
参考 http://docs.mongodb.org/manual/reference/command/group/

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

命令 aggregate
参量
{
    aggregate: <collection>,
    pipeline: [ <stage>, <...> ],
    explain: <true|false>,
    allowDiskUse: <true|false>,
    cursor: <cursor>
}
包装纸 db.collection.aggregate(<pipeline>, { explain: <true|false>, allowDiskUse: <true|false>, cursor: <cursor> } )
描述 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 ).

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 } } 
] 
})
参考 http://docs.mongodb.org/manual/reference/command/aggregate/

http://docs.mongodb.org/manual/reference/method/db.collection.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

有关更多详细信息,请参阅官方文档

命令 filemd5
参量
{ 
    filemd5: <object id>, 
    root: <root> 
}
描述 Returns the MD5 hashes for a single file stored using the GridFS specification.
In the shell, let us run the command: bin/mongofiles put bin/mongofiles

gridfs1

MongoDB Shell中,让我们发出命令:

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

gridfs2

参考 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 .

命令 eval
参量
{
    eval: <function>,
    args: [ <arg1>, <arg2> ... ],
    nolock: <true|false>
}
包装纸 db.eval(<function>, <arguments>)
描述 Provides the ability to evaluate JavaScript functions on the MongoDB server.
MongoDB Shell中,让我们发出命令:
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" ]
} )
参考 http://docs.mongodb.org/manual/reference/command/eval/

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

eval

命令 db.version()
描述 Returns the version of the MongoDB server instance.
In MongoDB shell, let us issue the command: db.version()

02.DB.VERSION

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

db.version()

命令 db.getMongo()
描述 Returns the current database connection.
In MongoDB shell, let us issue the command: db.getMongo()

02.DB.GETMONGO

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

db.getMongo()

命令 db.currentOp()
描述 Reports the current in-progress operations for the MongoDB database instance
In MongoDB shell, let us issue the command: db.currentOp()

02.DB.CURRENTOP

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

db.currentOp()

命令 db.killOp(<opid>)
描述 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.
参考 http://docs.mongodb.org/manual/reference/method/db.killOp/

db.killOp()

命令 buildInfo
包装纸 db.serverBuildInfo()
描述 Returns a build summary for the current MongoDB server instance.
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.

参考 http://docs.mongodb.org/manual/reference/command/buildInfo/

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

buildInfo

命令 hostInfo
包装纸 db.hostInfo()
描述 Returns information about the underlying system that MongoDB server instance is running on. Some of the returned fields are only included on some platforms.
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.

参考 http://docs.mongodb.org/manual/reference/command/hostInfo/

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

hostInfo

命令 serverStatus
包装纸 db.serverStatus()
描述 Returns the overview of the MongoDB server instance process state, including different collection statistics about the instance.
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.

参考 http://docs.mongodb.org/manual/reference/command/serverStatus/

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

serverStatus

命令 shutdown
包装纸 db.shutdownServer()
描述 Cleans up all database resources and then terminates the current MongoDB server instance process. 它应在管理数据库的上下文中运行。
MongoDB Shell中,让我们发出命令:
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.

参考 http://docs.mongodb.org/manual/reference/command/shutdown/

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

关掉

命令 getCmdLineOpts
描述 Outputs the command line options used to start the current MongoDB server instance. 它应在管理数据库的上下文中运行。
In MongoDB shell, let us issue the command: db.adminCommand( { getCmdLineOpts: 1 } )

02.GETCMDLINEOPTS

参考 http://docs.mongodb.org/manual/reference/command/getCmdLineOpts/

getCmdLineOpts

命令 top
描述 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

它应在管理数据库的上下文中运行。

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

02.TOP

Note: Only a fragment of the output is shown.

参考 http://docs.mongodb.org/manual/reference/command/top/

最佳

命令 getLog
参量
{ 
    getLog: <log> 
}
描述 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

它应在管理数据库的上下文中运行。

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

02.GETLOG

Note: Only a fragment of the output is shown.

参考 http://docs.mongodb.org/manual/reference/command/getLog/

getLog

命令 touch
参量
{ 
    touch: <collection>, 
    data: <true|false>, 
    index: <true|false> 
}
描述 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.
MongoDB Shell中,让我们发出命令:
db.createCollection( "mycoll" )
db.runCommand( { touch: "mycoll", index: true } )

02.TOUCH

参考 http://docs.mongodb.org/manual/reference/command/touch/

touch

命令 logRotate
描述 Allows rotating the MongoDB server instance logs to prevent a single log file from consuming too much disk space. 它应在管理数据库的上下文中运行。
In MongoDB shell, let us issue the command: db.adminCommand( { logRotate: 1 } )

02.LOGROTATE

参考 http://docs.mongodb.org/manual/reference/command/logRotate/

logRotate

命令 setParameter
参量
{ 
    <option>: <value> 
}
描述 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

它应在管理数据库的上下文中运行。

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

02.SETPARAMETER

参考 http://docs.mongodb.org/manual/reference/command/setParameter/

setParameter

命令 getParameter
参量
{ 
    <option>: <value> 
}
描述 Allows retrieving the value of MongoDB server instance options normally set on the command line. The <option> parameter follows the setParameter command specification. 它应在管理数据库的上下文中运行。
In MongoDB shell, let us issue the command: db.adminCommand( { getParameter: 1, “textSearchEnabled”: 1 } )

02.GETPARAMETER

参考 http://docs.mongodb.org/manual/reference/command/getParameter/

getParameter

9.接下来

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.

翻译自: https://www.javacodegeeks.com/2015/09/mongodb-shell-guide-operations-and-commands.html

mongodb shell

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值