MongoDB 命令记录

2023-07-17 16:58:05 浏览数 (2)

一下内容基于MongoDB 4.4.11版本。 命令行连接数据库方式:

  1. 直接输入mongo
  2. mongo mongodb://username:password@hostname/dbname。例子:mongo mongodb://admin:123456@123.1.2.3:12345/test01

1. MongoDB 主要命令描述

这里直接通过help命令的放回内容进行记录。 备注:这里描述的表、集合、文档,都是表达数据库表的意思。

1.1. help 命令

代码语言:javascript复制
> help												 关于mongodb主要方法的帮助
	db.help()                    关于数据库方法的帮助
	db.mycoll.help()             关于数据库表方法的帮助
	sh.help()                    分片方法的帮助
	rs.help()                    副本集方法的帮助
	help admin                   行政帮助
	help connect                 连接到数据库的帮助
	help keys                    键的快捷方式
	help misc                    misc things to know
	help mr                      mapreduce(一种分布式并行编程模型)

	show dbs                     展示所有数据库的名称
	show collections             展示当前数据库的所有集合(表)名称
	show users                   展示当前数据库的所有用户
	show profile                 显示时间为>= 1ms的最近的system.profile条目
	show logs                    显示可访问的log名称
	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                         退出mongo shell

1.2. db.help() 命令

代码语言:javascript复制
> db.help()
DB methods:
	db.adminCommand(nameOrDocument) - 切换到'admin' db,并运行命令 [只调用 db.runCommand(...)](目前不知道在哪使用)
	db.aggregate([pipeline], {options}) - 对该数据库执行无集合聚合;返回一个指针(目前不知道在哪使用)
	db.auth(username, password)(目前不知道在哪使用)
	db.cloneDatabase(fromhost) - will only function with MongoDB 4.0 and below
	db.commandHelp(name) returns the help for the command
	db.copyDatabase(fromdb, todb, fromhost) - will only function with MongoDB 4.0 and below
	db.createCollection(name, {size: ..., capped: ..., max: ...})
	db.createUser(userDocument)
	db.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions})
	db.currentOp() displays currently executing operations in the db
	db.dropDatabase(writeConcern)
	db.dropUser(username)
	db.eval() - deprecated
	db.fsyncLock() flush data to disk and lock server for backups
	db.fsyncUnlock() unlocks server following a db.fsyncLock()
	db.getCollection(cname) same as db['cname'] or db.cname
	db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
	db.getCollectionNames()
	db.getLastError() - just returns the err msg string
	db.getLastErrorObj() - return full status object
	db.getLogComponents()
	db.getMongo() get the server connection object
	db.getMongo().setSlaveOk() allow queries on a replication slave server
	db.getName()
	db.getProfilingLevel() - deprecated
	db.getProfilingStatus() - returns if profiling is on and slow threshold
	db.getReplicationInfo()
	db.getSiblingDB(name) get the db at the same server as this one
	db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
	db.hostInfo() get details about the server's host
	db.isMaster() check replica primary status
	db.killOp(opid) kills the current operation in the db
	db.listCommands() lists all the db commands
	db.loadServerScripts() loads all the myscripts in db.system.js
	db.logout()
	db.printCollectionStats()
	db.printReplicationInfo()
	db.printShardingStatus()
	db.printSlaveReplicationInfo()
	db.resetError()
	db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into {cmdObj: 1}
	db.serverStatus()
	db.setLogLevel(level,<component>)
	db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
	db.setVerboseShell(flag) display extra information in shell output
	db.setWriteConcern(<write concern doc>) - sets the write concern for writes to the db
	db.shutdownServer()
	db.stats()
	db.unsetWriteConcern(<write concern doc>) - unsets the write concern for writes to the db
	db.version() current version of the server
	db.watch() - opens a change stream cursor for a database to report on all  changes to its non-system collections.

1.3. db.collection.help() 命令

代码语言:javascript复制
> db.demo.help()
DBCollection help
	db.demo.find().help() - 展示 DBCursor 方法帮助
	db.demo.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j
	db.demo.count( query = {}, <optional params> ) - 计算匹配查询的文档数量,可选参数有:limit、skip、hint、maxTimeMS
	db.demo.countDocuments( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
	db.demo.estimatedDocumentCount( <optional params> ) - estimate the document count using collection metadata, optional parameters are: maxTimeMS
	db.demo.convertToCapped(maxBytes) - calls {convertToCapped:'demo', size:maxBytes}} command
	db.demo.createIndex(keypattern[,options])
	db.demo.createIndexes([keypatterns], <options>)
	db.demo.dataSize()
	db.demo.deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j
	db.demo.deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j
	db.demo.distinct( key, query, <optional params> ) - e.g. db.demo.distinct( 'x' ), optional parameters are: maxTimeMS
	db.demo.drop() drop the collection
	db.demo.dropIndex(index) - e.g. db.demo.dropIndex( "indexName" ) or db.demo.dropIndex( { "indexKey" : 1 } )
	db.demo.hideIndex(index) - e.g. db.demo.hideIndex( "indexName" ) or db.demo.hideIndex( { "indexKey" : 1 } )
	db.demo.unhideIndex(index) - e.g. db.demo.unhideIndex( "indexName" ) or db.demo.unhideIndex( { "indexKey" : 1 } )
	db.demo.dropIndexes()
	db.demo.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead
	db.demo.explain().help() - show explain help
	db.demo.reIndex()
	db.demo.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
	                                              e.g. db.demo.find( {x:77} , {name:1, x:1} )
	db.demo.find(...).count()
	db.demo.find(...).limit(n)
	db.demo.find(...).skip(n)
	db.demo.find(...).sort(...)
	db.demo.findOne([query], [fields], [options], [readConcern])
	db.demo.findOneAndDelete( filter, <optional params> ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS
	db.demo.findOneAndReplace( filter, replacement, <optional params> ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
	db.demo.findOneAndUpdate( filter, <update object or pipeline>, <optional params> ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
	db.demo.getDB() get DB object associated with collection
	db.demo.getPlanCache() get query plan cache associated with collection
	db.demo.getIndexes()
	db.demo.insert(obj)
	db.demo.insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j
	db.demo.insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j
	db.demo.mapReduce( mapFunction , reduceFunction , <optional params> )
	db.demo.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor
	db.demo.remove(query)
	db.demo.replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j
	db.demo.renameCollection( newName , <dropTarget> ) renames the collection.
	db.demo.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
	db.demo.save(obj)
	db.demo.stats({scale: N, indexDetails: true/false, indexDetailsKey: <index key>, indexDetailsName: <index name>})
	db.demo.storageSize() - includes free space allocated to this collection
	db.demo.totalIndexSize() - size in bytes of all the indexes
	db.demo.totalSize() - storage allocated for all data and indexes
	db.demo.update( query, <update object or pipeline>[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi, hint
	db.demo.updateOne( filter, <update object or pipeline>, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j, hint
	db.demo.updateMany( filter, <update object or pipeline>, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j, hint
	db.demo.validate( <full> ) - SLOW
	db.demo.getShardVersion() - only for use with sharding
	db.demo.getShardDistribution() - prints statistics about data distribution in the cluster
	db.demo.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function
	db.demo.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
	db.demo.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection
	db.demo.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection
	db.demo.latencyStats() - display operation latency histograms for this collection

1.4. help keys 命令

代码语言:javascript复制
> help keys
Tab completion and command history is available at the command prompt.
Some emacs keystrokes are available too:
  Ctrl-A start of line
  Ctrl-E end of line
  Ctrl-K del to end of line

Multi-line commands
You can enter a multi line javascript expression.  If parens, braces, etc. are not closed, you will see a new line 
beginning with '...' characters.  Type the rest of your expression.  Press Ctrl-C to abort the data entry if you
get stuck.

翻译为中文:

在命令提示符处可以使用制表符补全和命令历史记录。 一些emacs按键也可用:

  • Ctrl-A 去到行开始
  • Ctrl-E 去到行结束
  • Ctrl-K 删除整行

多行命令 您可以输入多行javascript表达式。如果括号、大括号等没有关闭,你会看到一个新行开始的……的字符。输入表达式的其余部分。按Ctrl-C中止数据输入,如果您被卡住了。

1.5. db.collection.find().help() 命令

代码语言:javascript复制
> db.HouseHold.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
	.pretty() - pretty print each document, possibly over multiple lines

MongoDB用户操作

转载自:https://blog.csdn.net/hbtj_1216/article/details/120875957

代码语言:javascript复制
use admin

db.createUser({
  user: 'admin',    // 用户名(自定义)
  pwd: 'Abc123  ',  // 密码(自定义)
  roles:[{
    role: 'root',   // 使用超级用户角色
    db: 'admin'     // 指定数据库
  }]
})

设置完成,可以通过指令 show users 查看是否设置成功。

代码语言:javascript复制
# 查看当前库下的用户
show users
# 删除用户
db.dropUser('testadmin')
# 修改用户密码
db.updateUser('admin', {pwd: '654321'})
# 密码认证
db.auth('admin', '654321')

角色描述

角色标识

数据库用户角色

read、readWrite

数据库管理角色

dbAdmin、dbOwner、userAdmin

集群管理角色

clusterAdmin、clusterManager、clusterMonitor、hostManager

备份恢复角色

backup、restore

所有数据库角色

readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、 dbAdminAnyDatabase

超级用户角色

root

查询 find()

查询函数

函数

描述

0 人点赞