记一些 mongodb 常用命令

// 常用命令
show dbs // 查看所有数据库列表
db // 查看当前连接的是哪个库
use test // 新建数据库 & 切换到test库 
db.dropDatabase() // 删库
show collections // 查看当前库下的集合(表)
db.test.insert({"name":"willian"}) // 创建集合并插入数据
db.test.drop() // 删除表
db.test.find() // 查询所有记录
db.test.find({"name":"zs"}) // 查询某条name为"zs"的记录
db.test.find().limit(5); // 查询前5条数据
db.test.find().skip(10); // 查询10条以后的数据
db.test.find({$or: [{age: 22}, {age: 25}]}); // or查询
db.userInfo.find({age: {$gte: 25}}).count(); // 查询age>=25的条数
db.test.distinct("name") // 去重
// 更改记录 query : update的查询条件
// update : update的对象和一些更新的操作符 upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入 
// multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新 writeConcern :可选,抛出异常的级别
db.collection.update( <query>, <update>, { upsert: <boolean>, multi: <boolean>, writeConcern: <document> } ) 
db.test.update({"name":"小明"},{$set:{"age":16}}) // 查找名字叫做小明的,把年龄更改为 16// query :(可选)删除的文档的条件 
// justOne : (可选)如果设为 true 或 1,则只删除一个文档 writeConcern :(可选)抛出异常的级别
db.test.remove( <query>, { justOne: <boolean>, writeConcern: <document> } ) 
db.test.remove({age: 12}) // 删除age为12的

db.addUser(username, password) // 添加数据库授权用户    
db.auth(username, password)  // 访问认证    
db.cloneDatabase(fromhost) // 克隆数据库    
db.copyDatabase(fromdb, todb, fromhost)  // 复制数据库    
db.createCollection(name, { size : ..., capped : ..., max : ... } ) // 创建表      
db.getCollectionNames() // 获取当前数据库的表名       
db.printCollectionStats()  // 打印各表的状态信息    
db.printReplicationInfo()  // 打印主数据库的复制状态信息    
db.printSlaveReplicationInfo()  // 打印从数据库的复制状态信息    
db.removeUser(username) // 删除数据库用户    
db.repairDatabase() // 修复数据库    
db.version() // 版本号// 表操作
db.test.count() // 统计表的行数    
db.test.dataSize() // 统计表数据的大小       
db.test.dropIndex(name)  // 删除指定索引    
db.test.dropIndexes() // 删除所有索引    
db.test.ensureIndex(keypattern,options)  // 增加索引  // 查看帮助-库操作-copy
db.help()

    db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]
    db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor
    db.auth(username, password)
    db.cloneDatabase(fromhost) - deprecated
    db.commandHelp(name) returns the help for the command
    db.copyDatabase(fromdb, todb, fromhost) - deprecated
    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

// 查看帮助-表操作-copy
db.test.help()

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

 

posted @ 2020-04-11 22:48  c-137Summer  阅读(215)  评论(0编辑  收藏  举报