MongoDB12-MongoDB相关命令

1、mongod命令

  • mongod命令的帮助说明
]# mongod --help
Options:
  --networkMessageCompressors arg (=snappy,zstd,zlib)
                                        用于网络消息的压缩器列表

General options:
  -h [ --help ]                         帮助信息
  --version                             显示版本信息
  -f [ --config ] arg                   指定附加选项的配置文件
  --configExpand arg                    在配置文件中处理展开指令(none, exec, rest)
  --port arg                            端口号(默认27017)
  --ipv6                                启用IPv6支持(默认禁用)
  --listenBacklog arg (=128)            设置套接字侦听积压大小
  --maxConns arg (=1000000)             最大同时连接数
  --pidfilepath arg                     pidfile的绝对路径(如果没有设置,则不创建pidfile)
  --timeZoneInfo arg                    time zone info目录的绝对路径。e.g. /usr/share/zoneinfo
  --nounixsocket                        禁止监听unix套接字
  --unixSocketPrefix arg                UNIX域套接字的目录(默认是/tmp)
  --filePermissions arg                 设置UNIX域套接字文件的权限(默认是0700)
  --fork                                服务器多进程
  -v [ --verbose ] [=arg(=v)]           信息详情(e.g. -vvvvv)
  --quiet                               静默输出
  --logpath arg                         设置日志文件(必须是一个文件名,而不是目录)
  --syslog                              记录到系统的syslog工具,而不是文件或标准输出
  --syslogFacility arg                  用于mongodb Syslog消息的Syslog设施
  --logappend                           将日志追加到日志文件中,而不是覆盖
  --logRotate arg                       设置日志文件循环行为(rename|reopen)
  --timeStampFormat arg                 日志消息中的时间戳所需的格式。 One of iso8601-utc or iso8601-local
  --setParameter arg                    设置可配置参数
  --bind_ip arg                         默认情况下,在localhost上监听以逗号分隔的ip地址列表
  --bind_ip_all                         绑定所有ip地址
  --noauth                              没有安全运行
  --transitionToAuth                    用于滚动访问控制升级。尝试通过传出连接进行身份验证,不管是否成功。接受传入连接,无论是否进行身份验证。
  --slowms arg (=100)                   配置文件和控制台日志的慢值
  --slowOpSampleRate arg (=1)           要包含在概要文件和控制台日志中的慢速操作的部分
  --profileFilter arg                   查询谓词以控制记录和分析哪些操作
  --auth                                安全运行
  --clusterIpSourceAllowlist arg        网络CIDR规范允许的来源' __system '访问
  --profile arg                         0=off 1=slow, 2=all
  --cpu                                 周期性显示cpu利用率和iowait利用率
  --sysinfo                             打印一些诊断系统信息
  --noscripting                         禁用脚本引擎
  --notablescan                         不允许表扫描
  --shutdown                            杀死正在运行的服务(用于初始化脚本)
  --keyFile arg                         用于集群鉴权的私钥
  --clusterAuthMode arg                 集群鉴权方式。(keyFile|sendKeyFile|sendX509|x509)

Replication options(复制选项):
  --oplogSize arg                       用于复制操作日志的大小(以MB为单位)。默认为磁盘空间的5%(i.e. large is good)

Replica set options(副本设置选项):
  --replSet arg                         arg is <setname>[/<optionalseedhostlist>]
  --enableMajorityReadConcern [=arg(=1)] (=1)            启用majority readConcern。enableMajorityReadConcern=false禁用

Sharding options(分片选项):
  --configsvr                           声明这是集群的一个配置数据库(默认端口是27019,默认目录是/data/configdb)
  --shardsvr                            声明这是一个集群的分片数据库(默认端口是27018)

Storage options(存储选项):
  --storageEngine arg                   使用什么存储引擎,默认为wiredTiger
  --dbpath arg                          数据目录(默认是/data/db)
  --directoryperdb                      每个数据库将存储在一个单独的目录中
  --syncdelay arg (=60)                 磁盘同步之间的秒数
  --journalCommitInterval arg (=100)    分组/批量提交的频率是多少(ms)
  --upgrade                             如果需要,升级db
  --repair                              对所有dbs运行修复
  --journal                             启用日志记录
  --nojournal                           禁用日志记录 (journaling is on by default for 64 bit)
  --oplogMinRetentionHours arg (=0)     在oplog中保留的最小小时数。默认值为0(关闭)。可以使用小数(e.g. 1.5 hours)

WiredTiger options(WiredTiger选项):
  --wiredTigerCacheSizeGB arg           分配给缓存的最大内存量;默认是物理内存的1/2
  --zstdDefaultCompressionLevel arg (=6)                 zstandard压缩器的默认压缩级别
  --wiredTigerJournalCompressor arg (=snappy)            日志记录使用的压缩器[none|snappy|zlib|zstd]
  --wiredTigerDirectoryForIndexes                        将索引和数据放在不同的目录中
  --wiredTigerCollectionBlockCompressor arg (=snappy)    采集数据的块压缩算法[none|snappy|zlib|zstd]
  --wiredTigerIndexPrefixCompression arg (=1)            在行存储页上使用前缀压缩
                                        

AWS IAM Options:
  --awsIamSessionToken arg              用于临时凭证的AWS会话令牌

Free Monitoring Options:
  --enableFreeMonitoring arg            启用无云监控(on|runtime|off)
  --freeMonitoringTag arg               无云监控标签

TLS Options:
  --tlsOnNormalPorts                    在配置的端口上使用TLS
  --tlsMode arg                         设置TLS操作模式(disabled|allowTLS|preferTLS|requireTLS)
  --tlsCertificateKeyFile arg           用于TLS的证书和密钥文件
  --tlsCertificateKeyFilePassword arg   TLS证书密钥文件中用于解锁密钥的密码
  --tlsClusterFile arg                  用于内部TLS认证的密钥文件
  --tlsClusterPassword arg              内部鉴权密钥文件密码
  --tlsCAFile arg                       TLS的证书颁发机构文件
  --tlsClusterCAFile arg                在入站连接期间用于验证远程连接的CA
  --tlsCRLFile arg                      TLS证书撤销列表文件
  --tlsDisabledProtocols arg            要禁用的TLS协议列表[TLS1_0,TLS1_1,TLS1_2,TLS1_3 ]
  --tlsAllowConnectionsWithoutCertificates               允许客户端连接而不提供证书
  --tlsAllowInvalidHostnames            允许服务器证书提供不匹配的主机名
  --tlsAllowInvalidCertificates         允许连接到证书无效的服务器
  --tlsFIPSMode                         启动时激活FIPS 140-2模式
  --tlsLogVersions arg                  TLS协议列表登录连接[TLS1_0,TLS1_1,TLS1_2 ,TLS1_3]

2、mongosh命令(MongoDB shell)

  • mongosh命令的帮助说明
]# mongosh --help
  $ mongosh [options] [db address] [file names (ending in .js or .mongodb)]
  Options:
    -h, --help                                 Show this usage information
    -f, --file [arg]                           Load the specified mongosh script
        --host [arg]                           要连接的服务器
        --port [arg]                           要连接的服务器的端口
        --version                              显示版本信息
        --verbose                              增加shell输出的详细信息
        --quiet                                静默输出
        --shell                                在执行文件后运行shell
        --nodb                                 不要在启动时连接到mongod--期望没有'db地址'参数
        --norc                                 启动时不运行'.mongoshrc.js'文件
        --eval [arg]                           评估javascript
        --json[=canonical|relaxed]             将eval的结果打印为扩展JSON,包括错误
        --retryWrites[=true|false]             在瞬时网络错误时自动重试写操作(Default: true)
  Authentication Options:
    -u, --username [arg]                       进行身份验证的用户名
    -p, --password [arg]                       进行身份验证的密码
        --authenticationDatabase [arg]         用户来源 (defaults to dbname)
        --authenticationMechanism [arg]        身份验证机制
        --awsIamSessionToken [arg]             AWS IAM临时会话令牌ID
        --gssapiServiceName [arg]              使用GSSAPI/Kerberos进行身份验证时使用的服务名
        --sspiHostnameCanonicalization [arg]   指定SSPI主机名规范化(无或转发,在Windows上可用)
        --sspiRealmOverride [arg]              指定SSPI服务器域(在Windows上可用)
  TLS Options:
        --tls                                  对所有连接使用TLS
        --tlsCertificateKeyFile [arg]          TLS协议的PEM证书/密钥文件
        --tlsCertificateKeyFilePassword [arg]  TLS时PEM文件中密钥的密码
        --tlsCAFile [arg]                      TLS的证书颁发机构文件
        --tlsAllowInvalidHostnames             允许连接到主机名不匹配的服务器
        --tlsAllowInvalidCertificates          允许连接到证书无效的服务器
        --tlsCertificateSelector [arg]         系统存储区中的TLS证书(仅限Windows和macOS)
        --tlsCRLFile [arg]                     指定包含证书吊销列表的.pem文件
        --tlsDisabledProtocols [arg]           禁用TLS协议列表[TLS1_0,TLS1_1,TLS1_2]
        --tlsUseSystemCA                       加载操作系统受信任证书列表
        --tlsFIPSMode                          启用系统TLS库的FIPS模式
  API version options:
        --apiVersion [arg]                     指定要连接的API版本
        --apiStrict                            使用严格的API版本模式
        --apiDeprecationErrors                 失败指定API版本的弃用命令
  FLE Options:
        --awsAccessKeyId [arg]                 AWS Access Key for FLE Amazon KMS
        --awsSecretAccessKey [arg]             AWS秘密密钥的FLE亚马逊KMS
        --awsSessionToken [arg]                可选AWS会话令牌ID
        --keyVaultNamespace [arg]              database.collection来存储加密的FLE参数
        --kmsURL [arg]                         测试参数以覆盖KMS端点的URL

3、其它

> help
	db.help()                    db方法的帮助
	db.mycoll.help()             集合方法的帮助
	sh.help()                    分片方法的帮助
	rs.help()                    副本集方法的帮助
	help admin                   administrative的帮助
	help connect                 正在连接db的帮助
	help keys                    键的快捷方式
	help misc                    misc things to know要知道的事情很多
	help mr                      mapreduce分布式

	show dbs                     显示数据库名称
	show collections             显示当前数据库中的集合
	show users                   显示当前数据库中的用户
	show profile                 显示最近system.profile条目,时间大于1ms
	show logs                    显示可访问的记录器名称
	show log [name]              打印内存中的最后一段日志,'global'是默认值
	use <db_name>                设置当前数据库
	db.mycoll.find()             在集合mycoll中列出对象
	db.mycoll.find( { a : 1 } )  列出mycoll中a == 1的对象
	it                           最后一行的计算结果;用于进一步迭代
	DBQuery.shellBatchSize = x   设置在shell上显示的默认项目数
	exit                         quit the mongo shell

============================================================

> db.mycoll.help()
	db.mycoll.find().help() - show DBCursor help

//删除集合
	db.mycoll.drop()
	db.mycoll.remove(query)

//插入数据
	db.mycoll.insert(obj)
	db.mycoll.insertOne( obj, <optional params> )
	db.mycoll.insertMany( [objects], <optional params> )

//查看数据
	db.mycoll.find([query],[fields])    #Query是一个可选的查询过滤器,Fields是返回字段的可选集合。例如,db.mycoll.find( {x:77} , {name:1, x:1} )
	db.mycoll.find(...).limit(n)
	db.mycoll.find(...).skip(n)
	db.mycoll.find(...).sort(...)
	db.mycoll.findOne([query], [fields], [options], [readConcern])

//聚集函数
	db.mycoll.count( query = {}, <optional params> )
	db.mycoll.find(...).count()
	db.mycoll.distinct( key, query, <optional params> )

//更新数据
	db.mycoll.update( query, <update object or pipeline>[, upsert_bool, multi_bool] )
	db.mycoll.updateOne( filter, <update object or pipeline>, <optional params> )
	db.mycoll.updateMany( filter, <update object or pipeline>, <optional params> )

	db.mycoll.findOneAndUpdate( filter, <update object or pipeline>, <optional params> )

	db.mycoll.save(obj)


//删除文档
	db.mycoll.deleteOne( filter, <optional params> )
	db.mycoll.deleteMany( filter, <optional params> )

//索引(回看4.9)
	db.mycoll.getIndexes()
	db.mycoll.createIndex(keypattern[,options])
	db.mycoll.createIndexes([keypatterns], <options>)

	db.mycoll.dropIndex(index) - e.g. db.mycoll.dropIndex( "indexName" ) or db.mycoll.dropIndex( { "indexKey" : 1 } )
	db.mycoll.hideIndex(index) - e.g. db.mycoll.hideIndex( "indexName" ) or db.mycoll.hideIndex( { "indexKey" : 1 } )
	db.mycoll.unhideIndex(index) - e.g. db.mycoll.unhideIndex( "indexName" ) or db.mycoll.unhideIndex( { "indexKey" : 1 } )
	db.mycoll.dropIndexes()

	db.mycoll.reIndex()
	db.mycoll.totalIndexSize() - 所有索引的字节大小

	db.mycoll.stats({scale: N, indexDetails: true/false, indexDetailsKey: <index key>, indexDetailsName: <index name>}) - 检查集合的大小

	db.mycoll.findOneAndDelete( filter, <optional params> ) - 删除第一个匹配的文档,可选参数有:projection, sort, maxTimeMS

	db.mycoll.findOneAndReplace( filter, replacement, <optional params> ) - 替换第一个匹配的文档,可选参数是: projection, sort, maxTimeMS, upsert, returnNewDocument

	db.mycoll.explain().help() - show explain help

	db.mycoll.bulkWrite( operations, <optional params> ) - 批量执行写操作,可选参数有:w、wtimeout、j

	db.mycoll.countDocuments( query = {}, <optional params> ) - count匹配查询的文档数量,可选参数有:limit、skip、hint、maxTimeMS
	db.mycoll.estimatedDocumentCount( <optional params> ) - 使用集合元数据估计文档计数,可选参数为:maxTimeMS
	db.mycoll.convertToCapped(maxBytes) - 调用{convertToCapped:'mycoll', size:maxBytes}} 命令

	db.mycoll.dataSize()
	db.mycoll.getDB() - 获取与集合关联的DB对象
	db.mycoll.getPlanCache() - 获取与集合关联的查询计划缓存

	db.mycoll.mapReduce( mapFunction , reduceFunction , <optional params> )
	db.mycoll.aggregate( [pipeline], <optional params> ) - 对集合执行聚合;返回一个指针

	db.mycoll.replaceOne( filter, replacement, <optional params> ) -  替换第一个匹配的文档,可选参数为:upsert, w, wtimeout, j
	db.mycoll.renameCollection( newName , <dropTarget> ) - 重命名集合。
	db.mycoll.runCommand( name , <options> ) - 使用给定的名称运行db命令,其中第一个参数是集合名称


	db.mycoll.storageSize() - 包括分配给此集合的可用空间

	db.mycoll.totalSize() - 为所有数据和索引分配的存储空间

	db.mycoll.validate( <full> ) - SLOW
	db.mycoll.getShardVersion() - 仅供与分片一起使用
	db.mycoll.getShardDistribution() - 打印集群中数据分布的统计信息
	db.mycoll.getSplitKeysForChunks( <maxChunkSize> ) - 计算所有块上的拆分点并返回拆分器函数
	db.mycoll.getWriteConcern() - 返回用于此集合上的任何操作的写关注点,如果设置了,则从server/db继承
	db.mycoll.setWriteConcern( <write concern doc> ) - 设置对集合写入的写入关注点
	db.mycoll.unsetWriteConcern( <write concern doc> ) - 取消对集合写入的写入关注
	db.mycoll.latencyStats() - 显示此集合的操作延迟直方图

============================================================

> db.help()

//删除数据库
	db.dropDatabase(writeConcern)

	db.serverStatus()
	db.version() - 服务器当前版本

	db.adminCommand(nameOrDocument) - 切换到'admin'数据库,并运行command[只调用db.runCommand(...)]
	db.aggregate([pipeline], {options}) - 对该数据库执行无集合的聚合;返回一个指针
	db.auth(username, password)
	db.commandHelp(name) - 返回命令帮助
	db.createUser(userDocument)
	db.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions})
	db.currentOp() - 显示数据库中当前正在执行的操作

	db.dropUser(username)
	db.eval() - 弃用
	db.fsyncLock() - 将数据刷新到磁盘并锁定服务器以备备份
	db.fsyncUnlock() - 在db.fsyncLock()之后解锁服务器
	db.getCollection(cname) - 与db['cname']或db.cname相同
	db.getCollectionInfos([filter]) - 返回一个列表,其中包含数据库集合的名称和选项
	db.getCollectionNames()
	db.getLastError() - 只返回err MSG字符串
	db.getLastErrorObj() - 返回完整的状态对象
	db.getLogComponents()
	db.getMongo() - 获取服务器连接对象
	db.getMongo().setSecondaryOk() - 允许在复制辅助服务器上进行查询
	db.getName()
	db.getProfilingLevel() - 弃用
	db.getProfilingStatus() - 如果性能分析开启且阈值较慢,则返回
	db.getReplicationInfo()
	db.getSiblingDB(name) - 在与这个相同的服务器上获取db
	db.getWriteConcern() - 返回在此数据库上的任何操作所使用的写关注点,如果设置,则从服务器对象继承
	db.hostInfo() - 获取关于服务器主机的详细信息
	db.isMaster() - 检查副本的主状态
	db.hello() - 检查副本的主状态
	db.killOp(opid) - 终止数据库中的当前操作
	db.listCommands() - 列出所有db命令
	db.loadServerScripts() - 加载db.system.js中的所有脚本
	db.logout()
	db.printCollectionStats()
	db.printReplicationInfo()
	db.printShardingStatus()
	db.printSecondaryReplicationInfo()
	db.rotateCertificates(message) - 轮换证书、crl和CA文件,并记录可选消息
	db.runCommand(cmdObj) - 运行数据库命令。如果cmdObj是一个字符串,把它变成{cmdObj: 1}

	db.setLogLevel(level,<component>)
	db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
	db.setVerboseShell(flag) - 在shell输出中显示额外的信息
	db.setWriteConcern(<write concern doc>) - 设置写入db的写入关注
	db.shutdownServer()
	db.stats()
	db.unsetWriteConcern(<write concern doc>) - 取消对db写入的写入关注

	db.watch() - 打开数据库的更改流游标,以报告对其非系统集合的所有更改。

============================================================

> rs.help()
	rs.status()                                     { replSetGetStatus : 1 } checks repl set status
	rs.initiate()                                   { replSetInitiate : null } initiates set with default settings
	rs.initiate(cfg)                                { replSetInitiate : cfg } initiates set with configuration cfg
	rs.conf()                                       get the current configuration object from local.system.replset
	rs.reconfig(cfg, opts)                          updates the configuration of a running replica set with cfg, using the given opts (disconnects)
	rs.reconfigForPSASet(memberIndex, cfg, opts)    updates the configuration of a Primary-Secondary-Arbiter (PSA) replica set while preserving majority writes
	                                                    memberIndex: index of the node being updated; cfg: the desired new config; opts: options passed in with the reconfig
	                                                    Not to be used with every configuration
	                                                    For more information, visit: https://docs.mongodb.com/manual/reference/method/rs.reconfigForPSASet/
	rs.add(hostportstr)                             add a new member to the set with default attributes (disconnects)
	rs.add(membercfgobj)                            add a new member to the set with extra attributes (disconnects)
	rs.addArb(hostportstr)                          add a new member which is arbiterOnly:true (disconnects)
	rs.stepDown([stepdownSecs, catchUpSecs])        step down as primary (disconnects)
	rs.syncFrom(hostportstr)                        make a secondary sync from the given member
	rs.freeze(secs)                                 make a node ineligible to become primary for the time specified
	rs.remove(hostportstr)                          remove a host from the replica set (disconnects)
	rs.secondaryOk()                                allow queries on secondary nodes

	rs.printReplicationInfo()                       check oplog size and time range
	rs.printSecondaryReplicationInfo()              check replica set members and replication lag
	db.isMaster()                                   check who is primary
	db.hello()                                      check who is primary

	reconfiguration helpers disconnect from the database so the shell will display
	an error, even if the command succeeds.

============================================================

> db.mycoll.find().help()
find(<predicate>, <projection>) modifiers
	.sort({...})
	.limit(<n>)
	.skip(<n>)
	.batchSize(<n>) - sets the number of docs to return per getMore
	.collation({...})
	.hint({...})
	.readConcern(<level>)
	.readPref(<mode>, <tagset>)
	.count(<applySkipLimit>) - total # of objects matching query. by default ignores skip,limit
	.size() - total # of objects cursor would return, honors skip,limit
	.explain(<verbosity>) - accepted verbosities are {'queryPlanner', 'executionStats', 'allPlansExecution'}
	.min({...})
	.max({...})
	.maxTimeMS(<n>)
	.comment(<comment>)
	.tailable(<isAwaitData>)
	.noCursorTimeout()
	.allowPartialResults()
	.returnKey()
	.showRecordId() - adds a $recordId field to each returned object
	.allowDiskUse() - allow using disk in completing the query

Cursor methods
	.toArray() - iterates through docs and returns an array of the results
	.forEach(<func>)
	.map(<func>)
	.hasNext()
	.next()
	.close()
	.objsLeftInBatch() - returns count of docs left in current batch (when exhausted, a new getMore will be issued)
	.itcount() - iterates through documents and counts them
	.getClusterTime() - returns the read timestamp for snapshot reads
	.pretty() - pretty print each document, possibly over multiple lines


=========================================================

http://docs.mongodb.com/database-tools/mongodump/ 
]# mongodump --help
Usage:
  mongodump <options> <connection-string>

将正在运行的服务器的内容导出到.bson文件中。



用-d指定数据库,用-c指定集合,以便只转储该数据库或集合。

general options:
      --help                                                print usage
      --version                                             print the tool version and exit
      --config=                                             配置文件的路径

verbosity options:
  -v, --verbose=<level>                                     more detailed log output (include multiple times for more verbosity, e.g. -vvvvv, or specify a numeric value, e.g. --verbose=N)
      --quiet                                               hide all log output

connection options:
  -h, --host=<hostname>                                     要连接的Mongodb主机(setname/host1,host2 for replica sets)
      --port=<port>                                         服务器端口(can also use --host hostname:port)

ssl options:
      --ssl                                                 connect to a mongod or mongos that has ssl enabled
      --sslCAFile=<filename>                                the .pem file containing the root certificate chain from the certificate
                                                            authority
      --sslPEMKeyFile=<filename>                            the .pem file containing the certificate and key
      --sslPEMKeyPassword=<password>                        the password to decrypt the sslPEMKeyFile, if necessary
      --sslCRLFile=<filename>                               the .pem file containing the certificate revocation list
      --sslFIPSMode                                         use FIPS mode of the installed openssl library
      --tlsInsecure                                         bypass the validation for server's certificate chain and host name

authentication options:
  -u, --username=<username>                                 username for authentication
  -p, --password=<password>                                 password for authentication
      --authenticationDatabase=<database-name>              database that holds the user's credentials
      --authenticationMechanism=<mechanism>                 authentication mechanism to use
      --awsSessionToken=<aws-session-token>                 session token to authenticate via AWS IAM

kerberos options:
      --gssapiServiceName=<service-name>                    service name to use when authenticating using GSSAPI/Kerberos (default:
                                                            mongodb)
      --gssapiHostName=<host-name>                          hostname to use when authenticating using GSSAPI/Kerberos (default: <remote
                                                            server's address>)

namespace options:
  -d, --db=<database-name>                                  要备份的数据库
  -c, --collection=<collection-name>                        要备份的集合

uri options:
      --uri=mongodb-uri                                     mongodb uri connection string

query options:
  -q, --query=                                              查询过滤器,作为v2扩展JSON字符串, e.g., '{"x":{"$gt":1}}'
      --queryFile=                                          包含查询筛选器的文件的路径 (v2 Extended JSON)
      --readPreference=<string>|<json>                      指定一个首选项模式 (e.g. 'nearest') 或者首选项json对象(e.g. '{mode: "nearest", tagSets: [{a: "b"}], maxStalenessSeconds: 123}')

output options:
  -o, --out=<directory-path>                                输出目录,或'-'用于标准输出(default: 'dump')
      --gzip                                                用Gzip压缩存档或集合输出
      --oplog                                               使用oplog进行时间点快照
      --archive=<file-path>                                 将存档转储到指定的路径。如果指定flag而不指定值,则将归档文件写入stdout
      --dumpDbUsersAndRoles                                 转储指定数据库的用户和角色定义
      --excludeCollection=<collection-name>                 要从转储中排除的集合(可以多次指定以排除其他集合)
      --excludeCollectionsWithPrefix=<collection-prefix>    从转储中排除具有给定前缀的所有集合(可以多次指定以排除其他前缀)
  -j, --numParallelCollections=                             要并行转储的集合数量
      --viewsAsCollections                                  将视图转储为普通集合及其生成的数据,忽略标准集合

=========================================================
http://docs.mongodb.com/database-tools/mongorestore/

]# mongorestore --help
Usage:
  mongorestore <options> <connection-string> <directory or file to restore>
将mongodb生成的备份恢复到运行中的服务器。
用-d指定数据库从目标目录恢复单个数据库,或者使用-d和-c从单个.bson文件恢复单个集合。

general options:
      --help                                                print usage
      --version                                             print the tool version and exit
      --config=                                             path to a configuration file

verbosity options:
  -v, --verbose=<level>                                     more detailed log output (include multiple times for more verbosity, e.g. -vvvvv, or specify a numeric value, e.g. --verbose=N)
      --quiet                                               hide all log output

connection options:
  -h, --host=<hostname>                                     mongodb host to connect to (setname/host1,host2 for replica sets)
      --port=<port>                                         server port (can also use --host hostname:port)

ssl options:
      --ssl                                                 connect to a mongod or mongos that has ssl enabled
      --sslCAFile=<filename>                                the .pem file containing the root certificate chain from the certificate authority
      --sslPEMKeyFile=<filename>                            the .pem file containing the certificate and key
      --sslPEMKeyPassword=<password>                        the password to decrypt the sslPEMKeyFile, if necessary
      --sslCRLFile=<filename>                               the .pem file containing the certificate revocation list
      --sslFIPSMode                                         use FIPS mode of the installed openssl library
      --tlsInsecure                                         bypass the validation for server's certificate chain and host name

authentication options:
  -u, --username=<username>                                 username for authentication
  -p, --password=<password>                                 password for authentication
      --authenticationDatabase=<database-name>              database that holds the user's credentials
      --authenticationMechanism=<mechanism>                 authentication mechanism to use
      --awsSessionToken=<aws-session-token>                 session token to authenticate via AWS IAM

kerberos options:
      --gssapiServiceName=<service-name>                    service name to use when authenticating using GSSAPI/Kerberos (default: mongodb)
      --gssapiHostName=<host-name>                          hostname to use when authenticating using GSSAPI/Kerberos (default: <remote server's address>)

namespace options:
  -d, --db=<database-name>                                  要恢复的数据库
  -c, --collection=<collection-name>                        要恢复的集合

uri options:
      --uri=mongodb-uri                                     mongodb uri connection string

namespace options:
      --excludeCollection=<collection-name>                 弃用;要在恢复期间跳过的集合(可以多次指定以排除其他集合)
      --excludeCollectionsWithPrefix=<collection-prefix>    弃用;在恢复过程中要跳过的具有给定前缀的集合(可以多次指定以排除其他前缀)
      --nsExclude=<namespace-pattern>                       排除匹配名称空间
      --nsInclude=<namespace-pattern>                       包括匹配名称空间
      --nsFrom=<namespace-pattern>                          重命名匹配的命名空间,必须有匹配的nsTo
      --nsTo=<namespace-pattern>                            重命名匹配的命名空间,必须有匹配的nsFrom

input options:
      --objcheck                                            在插入之前验证所有对象
      --oplogReplay                                         重放日志以进行时间点恢复
      --oplogLimit=<seconds>[:ordinal]                      只在提供的时间戳之前包含oplog条目
      --oplogFile=<filename>                                用于重放Oplog的Oplog文件
      --archive=<filename>                                  从指定的归档文件恢复转储。如果指定flag而不指定值,则从stdin读取存档
      --restoreDbUsersAndRoles                              恢复给定数据库的用户和角色定义
      --dir=<directory-name>                                输入目录,使用'-'作为stdin
      --gzip                                                减压gzip输入

restore options:
      --drop                                                在导入之前删除每个集合
      --dryRun                                              不导入任何内容即可查看摘要。建议用冗长
      --writeConcern=<write-concern>                        写相关的选项e.g. --writeConcern majority, --writeConcern '{w: 3, wtimeout: 500, fsync: true, j: true}'
      --noIndexRestore                                      不恢复索引
      --convertLegacyIndexes                                删除无效的索引选项并重写遗留选项值 (e.g. true becomes 1).
      --noOptionsRestore                                    不要恢复收集选项
      --keepIndexVersion                                    不要更新索引版本
      --maintainInsertionOrder                              按照文档在输入源中的出现顺序恢复文档。默认情况下,插入将以任意顺序执行。设置此标志还启用--stopOnError行为,并限制NumInsertionWorkersPerCollection为1。
  -j, --numParallelCollections=                             要并行恢复的集合数量
      --numInsertionWorkersPerCollection=                   每个集合要并发运行的插入操作数
      --stopOnError                                         在插入过程中遇到任何错误后停止。默认情况下,mongorestore将尝试通过文档验证和DuplicateKey错误继续执行,但启用此选项后,该工具将停止。即使启用了此选项,也可能会在遇到错误后插入少量文档;使用--maintainInsertionOrder在错误发生后立即停止
      --bypassDocumentValidation                            绕过文档验证
      --preserveUUID                                        保留原始集合uuid(默认关闭,需要删除)
      --fixDottedHashIndex                                  当启用时,虚线字段上的所有散列索引将被创建为目标上的单字段升序索引

=========================================================

]# mongoexport --help
Usage:
  mongoexport <options> <connection-string>

Export data from MongoDB in CSV or JSON format.

Connection strings must begin with mongodb:// or mongodb+srv://.

See http://docs.mongodb.com/database-tools/mongoexport/ for more information.

general options:
      --help                                      print usage
      --version                                   print the tool version and exit
      --config=                                   path to a configuration file

verbosity options:
  -v, --verbose=<level>                           more detailed log output (include multiple times for more verbosity, e.g. -vvvvv, or specify a numeric value, e.g. --verbose=N)
      --quiet                                     hide all log output

connection options:
  -h, --host=<hostname>                           mongodb host to connect to (setname/host1,host2 for replica sets)
      --port=<port>                               server port (can also use --host hostname:port)

ssl options:
      --ssl                                       connect to a mongod or mongos that has ssl enabled
      --sslCAFile=<filename>                      the .pem file containing the root certificate chain from the certificate authority
      --sslPEMKeyFile=<filename>                  the .pem file containing the certificate and key
      --sslPEMKeyPassword=<password>              the password to decrypt the sslPEMKeyFile, if necessary
      --sslCRLFile=<filename>                     the .pem file containing the certificate revocation list
      --sslFIPSMode                               use FIPS mode of the installed openssl library
      --tlsInsecure                               bypass the validation for server's certificate chain and host name

authentication options:
  -u, --username=<username>                       username for authentication
  -p, --password=<password>                       password for authentication
      --authenticationDatabase=<database-name>    database that holds the user's credentials
      --authenticationMechanism=<mechanism>       authentication mechanism to use
      --awsSessionToken=<aws-session-token>       session token to authenticate via AWS IAM

kerberos options:
      --gssapiServiceName=<service-name>          service name to use when authenticating using GSSAPI/Kerberos (default: mongodb)
      --gssapiHostName=<host-name>                hostname to use when authenticating using GSSAPI/Kerberos (default: <remote server's address>)

namespace options:
  -d, --db=<database-name>                        database to use
  -c, --collection=<collection-name>              collection to use

uri options:
      --uri=mongodb-uri                           mongodb uri connection string

output options:
  -f, --fields=<field>[,<field>]*                 字段名列表 e.g. -f "name,age"
      --fieldFile=<filename>                      带字段名的文件,每行1个
      --type=<type>                               输出格式,可以是json或CSV
  -o, --out=<filename>                            输出文件;如果未指定,则使用stdout
      --jsonArray                                 输出到JSON数组,而不是每行一个对象
      --pretty                                    输出JSON格式,人可读
      --noHeaderLine                              导出CSV数据,第一行不包含字段名列表
      --jsonFormat=<type>                         扩展的JSON格式输出,canonical或relaxed(default: relaxed)

querying options:
  -q, --query=<json>                              查询过滤器,作为JSON字符串, e.g., '{x:{$gt:1}}'
      --queryFile=<filename>                      包含查询筛选器的文件的路径(JSON)
      --readPreference=<string>|<json>            指定首选模式(例如:'nearest')或首选项json对象(e.g. '{mode: "nearest", tagSets: [{a: "b"}], maxStalenessSeconds: 123}')
      --forceTableScan                            强制扫描表(不要使用$snapshot或提示_id)。已弃用,因为这是WiredTiger的默认行为
      --skip=<count>                              要跳过的文档数量
      --limit=<count>                             限制要导出的文档数量
      --sort=<json>                               排序顺序,作为JSON字符串, e.g. '{x:1}'
      --assertExists                              如果指定,则如果集合不存在,则导出失败

==================================================

]# mongoimport --help
Usage:
  mongoimport <options> <connection-string> <file> 

Import CSV, TSV or JSON data into MongoDB. If no file is provided, mongoimport reads from stdin.

Connection strings must begin with mongodb:// or mongodb+srv://.

See http://docs.mongodb.com/database-tools/mongoimport/ for more information.

general options:
      --help                                      print usage
      --version                                   print the tool version and exit
      --config=                                   path to a configuration file

verbosity options:
  -v, --verbose=<level>                           more detailed log output (include multiple times for more verbosity, e.g. -vvvvv, or
                                                  specify a numeric value, e.g. --verbose=N)
      --quiet                                     hide all log output

connection options:
  -h, --host=<hostname>                           mongodb host to connect to (setname/host1,host2 for replica sets)
      --port=<port>                               server port (can also use --host hostname:port)

ssl options:
      --ssl                                       connect to a mongod or mongos that has ssl enabled
      --sslCAFile=<filename>                      the .pem file containing the root certificate chain from the certificate authority
      --sslPEMKeyFile=<filename>                  the .pem file containing the certificate and key
      --sslPEMKeyPassword=<password>              the password to decrypt the sslPEMKeyFile, if necessary
      --sslCRLFile=<filename>                     the .pem file containing the certificate revocation list
      --sslFIPSMode                               use FIPS mode of the installed openssl library
      --tlsInsecure                               bypass the validation for server's certificate chain and host name

authentication options:
  -u, --username=<username>                       username for authentication
  -p, --password=<password>                       password for authentication
      --authenticationDatabase=<database-name>    database that holds the user's credentials
      --authenticationMechanism=<mechanism>       authentication mechanism to use
      --awsSessionToken=<aws-session-token>       session token to authenticate via AWS IAM

kerberos options:
      --gssapiServiceName=<service-name>          service name to use when authenticating using GSSAPI/Kerberos (default: mongodb)
      --gssapiHostName=<host-name>                hostname to use when authenticating using GSSAPI/Kerberos (default: <remote server's
                                                  address>)

namespace options:
  -d, --db=<database-name>                        database to use
  -c, --collection=<collection-name>              collection to use

uri options:
      --uri=mongodb-uri                           mongodb uri connection string

input options:
  -f, --fields=<field>[,<field>]*                 字段列表, e.g. -f name,age
      --fieldFile=<filename>                      带字段名的文件,每行1个
      --file=<filename>                           要导入的文件;如果未指定,则使用stdin
      --headerline                                使用输入源中的第一行作为字段列表(CSV and TSV only)
      --jsonArray                                 将输入源作为JSON数组
      --parseGrace=<grace>                        控制类型强制转换失败时的行为-其中之一: autoCast, skipField, skipRow, stop (default: stop)
      --type=<type>                               导入文件的格式: json, csv, or tsv
      --columnsHaveTypes                          indicates that the field list (from --fields, --fieldsFile, or --headerline) specifies
                                                  types; They must be in the form of '<colName>.<type>(<arg>)'. The type can be one of:
                                                  auto, binary, boolean, date, date_go, date_ms, date_oracle, decimal, double, int32,
                                                  int64, string. For each of the date types, the argument is a datetime layout string. For
                                                  the binary type, the argument can be one of: base32, base64, hex. All other types take
                                                  an empty argument. Only valid for CSV and TSV imports. e.g. zipcode.string(),
                                                  thumbnail.binary(base64)
      --legacy                                    使用传统的扩展JSON格式
      --useArrayIndexFields                       指示字段名可能包含应用于在导入期间构造数组的数组索引(例如foo.0,foo.1)。索引必须从0开始,按顺序递增(foo.1,foo.0 would fail).

ingest options:
      --drop                                      在插入文档之前删除集合
      --ignoreBlanks                              忽略CSV和TSV中空值的字段
      --maintainInsertionOrder                    按照文档在输入源中的出现顺序插入文档。默认情况下,插入将以任意顺序执行。设置这个标志还启用——stopOnError行为,并限制NumInsertionWorkers为1。
  -j, --numInsertionWorkers=<number>              要并发运行的插入操作的数目
      --stopOnError                               在导入过程中遇到任何错误后停止。
      --mode=[insert|upsert|merge|delete]         insert:只插入,跳过匹配的文档。upsert:插入新文档或替换现有文档。merge:插入新文档或修改现有文档。delete:只删除匹配的文档。如果upsert字段匹配多个文档,则只删除一个文档。(默认值:插入)
      --upsertFields=<field>[,<field>]*           当——mode设置为upsert或merge时,查询部分的逗号分隔字段
      --writeConcern=<write-concern-specifier>    写关心选项,例如——writeConcern majority,——writeConcern'{w: 3, wtimeout: 500, fsync: true, j: true}'
      --bypassDocumentValidation                  绕过文档验证

1

#                                                                                                                                #
posted @ 2022-10-02 21:36  麦恒  阅读(384)  评论(0编辑  收藏  举报