mongodb安装
参考安装教程:Linux Centos 7安装MongoDB(简单!详细!)
进入mongo数据库
# mongo
mongodb查看版本
方法一:
# mongo
> db.version()
3.4.24
方法二:
# mongo --version
MongoDB shell version v3.4.24
方法三
# mongod --version
db version v3.4.24
查看所有数据库
> 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 names
show collections show collections in current database
show users show users in current database
show profile show most recent system.profile entries with time >= 1ms
show logs show the accessible logger names
show log [name] prints out the last segment of log in memory, 'global' is default
use <db_name> set current database
db.foo.find() list objects in collection foo
db.foo.find( { a : 1 } ) list objects in foo where a == 1
it result of the last line evaluated; use to further iterate
DBQuery.shellBatchSize = x set default number of items to display on shell
exit 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)
db.commandHelp(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 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.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,<component>)
db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
db.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the db
db.unsetWriteConcern( <write concern doc> ) - 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, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j
db.user.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
db.user.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
db.user.convertToCapped(maxBytes) - calls {convertToCapped:'user', size:maxBytes}} command
db.user.createIndex(keypattern[,options])
db.user.createIndexes([keypatterns], <options>)
db.user.dataSize()
db.user.deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j
db.user.deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j
db.user.distinct( key, query, <optional params> ) - 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()
db.user.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead
db.user.explain().help() - show explain help
db.user.reIndex()
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, <optional params> ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS
db.user.findOneAndReplace( filter, replacement, <optional params> ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
db.user.findOneAndUpdate( filter, update, <optional params> ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
db.user.getDB() get DB object associated with collection
db.user.getPlanCache() get query plan cache associated with collection
db.user.getIndexes()
db.user.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
db.user.insert(obj)
db.user.insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j
db.user.insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j
db.user.mapReduce( mapFunction , reduceFunction , <optional params> )
db.user.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor
db.user.remove(query)
db.user.replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j
db.user.renameCollection( newName , <dropTarget> ) renames the collection.
db.user.runCommand( name , <options> ) 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: <index key>, indexDetailsName: <index name>})*
db.user.storageSize() - includes free space allocated to this collection
db.user.totalIndexSize() - size in bytes of all the indexes
db.user.totalSize() - 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, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j
db.user.updateMany( filter, update, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j
db.user.validate( <full> ) - SLOW
db.user.getShardVersion() - only for use with sharding
db.user.getShardDistribution() - prints statistics about data distribution in the cluster
db.user.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function
db.user.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
db.user.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection
db.user.unsetWriteConcern( <write concern doc> ) - 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" : "yapi.testread",
"userId" : BinData(4,"C11txSWuTpO2Go16mfuASA=="),
"user" : "testread",
"db" : "yapi",
"roles" : [
{
"role" : "read",
"db" : "yapi"
}
]
}
{
"_id" : "yapi.testrw",
"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
删除用户
> db.removeUser('testrw')
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.com'}).sort({'Dt',-1})
> db.deliver_status.find().sort({'Ct':-1}).limit(1)
count操作
> db.user_addr.count()
distinct操作
db.foo.distinct('msg')
网友评论