进入mongo数据库
mongo localhost:27017/admin -u pfnieadmin -p 123456
mongodb查看版本
db.version()
查看所有数据库
show dbs
admin 0.000GB
local 0.000GB
yapi 0.224GB
切换数据库
use yapi
switched to db yapi
查看当前数据库
db
yapi
查看当前数据库下的所有表(或叫collection)
show collections
adv_mock
adv_mock_case
avatar
follow
group
identitycounters
interface
interface_auto_sync
interface_case
interface_cat
interface_col
log
project
statis_mock
storage
token
user
wiki
查看帮助命令
help
db.help() help on db methods
db.mycoll.help() help on collection methods
sh.help() sharding helpers
rs.help() replica set helpers
help admin administrative help
help connect connecting to a db help
help keys key shortcuts
help misc misc things to know
help mr mapreduce
show dbs show database namesshow collections show collections in current databaseshow users show users in current databaseshow profile show most recent system.profile entries with time >= 1msshow logs show the accessible logger namesshow log [name] prints out the last segment of log in memory, 'global' is defaultuse <db_name> set current databasedb.foo.find() list objects in collection foodb.foo.find( { a : 1 } ) list objects in foo where a == 1it result of the last line evaluated; use to further iterateDBQuery.shellBatchSize = x set default number of items to display on shellexit quit the mongo shell
查看当前库支持哪些方法
db.help()
DB methods:
db.adminCommand(nameOrDocument) - switches to ‘admin’ db, and runs command [ just calls db.runCommand(…) ]
db.auth(username, password)
db.cloneDatabase(fromhost)
dbmandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost)
db.createCollection(name, { size : …, capped : …, max : … } )
db.createView(name, viewOn, [ { $operator: {…}}, … ], { viewOptions } )
db.createUser(userDocument)
db.currentOp() displays currently executing operations in the db
db.dropDatabase()
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 dbame
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.getPrevError()
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 scripts in db.system.js
db.logout()
db.printCollectionStats()
db.printReplicationInfo()
db.printShardingStatus()
db.printSlaveReplicationInfo()
db.dropUser(username)
db.repairDatabase()
db.resetError()
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }
db.serverStatus()
db.setLogLevel(level,)
db.setProfilingLevel(level,) 0=off 1=slow 2=all
db.setWriteConcern( ) - sets the write concern for writes to the db
db.unsetWriteConcern( ) - unsets the write concern for writes to the db
db.setVerboseShell(flag) display extra information in shell output
db.shutdownServer()
db.stats()
db.version() current version of the server
当前数据库下的表或者表collection支持的方法
db.user.help()
DBCollection help
db.user.find().help() - show DBCursor help
db.user.bulkWrite( operations, ) - bulk execute write operations, optional parameters are: w, wtimeout, j
unt( query = {}, ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
pyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
vertToCapped(maxBytes) - calls {convertToCapped:‘user’, size:maxBytes}} command
ateIndex(keypattern[,options])
ateIndexes([keypatterns], )
db.user.dataSize()
db.user.deleteOne( filter, ) - delete first matching document, optional parameters are: w, wtimeout, j
db.user.deleteMany( filter, ) - delete all matching documents, optional parameters are: w, wtimeout, j
db.user.distinct( key, query, ) - e.g. db.user.distinct( ‘x’ ), optional parameters are: maxTimeMS
db.user.drop() drop the collection
db.user.dropIndex(index) - e.g. db.user.dropIndex( “indexName” ) or db.user.dropIndex( { “indexKey” : 1 } )
db.user.dropIndexes()
sureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead
plain().help() - show explain help
Index()
db.user.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
e.g. db.user.find( {x:77} , {name:1, x:1} )
db.user.find(…).count()
db.user.find(…).limit(n)
db.user.find(…).skip(n)
db.user.find(…).sort(…)
db.user.findOne([query], [fields], [options], [readConcern])
db.user.findOneAndDelete( filter, ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS
db.user.findOneAndReplace( filter, replacement, ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
db.user.findOneAndUpdate( filter, update, ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
DB() get DB object associated with collection
PlanCache() get query plan cache associated with collection
Indexes()
up( { key : …, initial: …, reduce : …[, cond: …] } )
db.user.insert(obj)
db.user.insertOne( obj, ) - insert a document, optional parameters are: w, wtimeout, j
db.user.insertMany( [objects], ) - insert multiple documents, optional parameters are: w, wtimeout, j
db.user.mapReduce( mapFunction , reduceFunction , )
db.user.aggregate( [pipeline], ) - performs an aggregation on a collection; returns a cursor
ve(query)
placeOne( filter, replacement, ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j
ameCollection( newName , ) renames the collection.
db.user.runCommand( name , ) runs a db command with the given name where the first param is the collection name
db.user.save(obj)
db.user.stats({scale: N, indexDetails: true/false, indexDetailsKey: , indexDetailsName: })*
db.user.storageSize() - includes free space allocated to this collection
alIndexSize() - size in bytes of all the indexes
alSize() - storage allocated for all data and indexes
db.user.update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi
db.user.updateOne( filter, update, ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j
db.user.updateMany( filter, update, ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j
db.user.validate( ) - SLOW
ShardVersion() - only for use with sharding
ShardDistribution() - prints statistics about data distribution in the cluster
SplitKeysForChunks( ) - calculates split points over all chunks and returns splitter function
WriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
db.user.setWriteConcern( ) - sets the write concern for writes to the collection
db.user.unsetWriteConcern( ) - unsets the write concern for writes to the collection
db.user.latencyStats() - display operation latency histograms for this collection
创建普通用户
1.进入要授权的数据库
use yapi
switched to db yapi
2.创建只读用户
db.createUser({user: “testread”,pwd: “testreadpass”,roles: [{ role: “read”, db: “yapi” } ]})
Successfully added user: {
“user” : “testread”,
“roles” : [
{
“role” : “read”,
“db” : “yapi”
}
]
}
3.创建读写用户
db.createUser({user: “testrw”,pwd: “testrwpass”,roles: [{ role: “readWrite”, db: “yapi” } ]})
Successfully added user: {
“user” : “testrw”,
“roles” : [
{
“role” : “readWrite”,
“db” : “yapi”
}
]
}
查看所有用户
show users
{
“_id” : “stread”,
“userId” : BinData(4,“C11txSWuTpO2Go16mfuASA==”),
“user” : “testread”,
“db” : “yapi”,
“roles” : [
{
“role” : “read”,
“db” : “yapi”
}
]
}
{
“_id” : “strw”,
“userId” : BinData(4,“6SIt7Uc0Q0q5tf09BGZPjw==”),
“user” : “testrw”,
“db” : “yapi”,
“roles” : [
{
“role” : “readWrite”,
“db” : “yapi”
}
]
}
用户认证
1.认证成功会返回1
db.auth(‘testrw’,‘testrwpass’)
1
2.认证失败会返回0
db.auth(‘testrw’,‘testrwpass1’)
Error: Authentication failed.
0
删除用户
WARNING: db.removeUser has been deprecated, please use db.dropUser instead
true
查询表数据
查询所有数据
db.user.find()
根据条件查找表数据
db.user.find({role:‘admin’})
根据条件检索10条记录
db.user.find().limit(10)
sort排序
db.deliver_status.find({‘From’:‘yushunzhi@sohu’}).sort({‘Dt’,-1})
db.deliver_status.find().sort({‘Ct’:-1}).limit(1)
count操作
db.unt()
distinct操作
db.foo.distinct(‘msg’)
分类: mongodb
本文发布于:2024-01-29 05:18:25,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170647671012969.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |