Remember some common commands of mongodb

// Common command 
show dbs // View the list of all databases 
db // Check which library is currently connected
 use test // Create a new database & switch to the test database 
db.dropDatabase () // Delete library 
show collections // View the current library Collection (table) 
db.test. Insert ({"name": "willian"}) // Create collection and insert data 
db.test. Drop () // Delete table 
db.test.find () // Query all Record 
db.test.find ({"name": "zs"}) // Query a record whose name is "zs" 
db.test.find (). Limit ( 5 ); // Query the first 5 data 
db.test.find ( ).skip(10 ); // Query 10 data after 
db.test.find ({$ or : [ {age: 22}, {age: 25} ] }); // or query 
db.userInfo.find ({age: {$ gte: 25 }}). count (); // Query the number of 
items with age > = 25 db.test. distinct ("name") // Deduplication
 // Change the record query: update query conditions
 //  update : update object and some update operator upsert: optional, this parameter means, if there is no update record, whether to insert objNew, true is inserted, the default is false, not inserted 
 multi: optional, mongodb default is False, only update the first record found. If this parameter is true, update all records detected by the condition. writeConcern: optional, throw exception level 
db.collection //update ( < query > , < update > , {upsert: < boolean > , multi: < boolean > , writeConcern: < document > }) 
db.test. update ({"name": "小 明"}, {$ set : {"age": 16 }}) // Find the name of Xiaoming, change the age to 16 years old
 // query: (optional) conditions for deleted documents 
 // justOne: (optional) if set to true or 1 , Then only delete one document writeConcern: (optional) the level at which the exception was thrown 
db.test.remove ( < query > , {justOne: < boolean > , writeConcern: < document > }) 
db.test.remove ({age: 12 } ) // Delete 

db.addUser (username, password) with age 12 // Add database authorized user     
db.auth (username, password)   // Access authentication     
db.cloneDatabase (fromhost) // Clone database     
db.copyDatabase (fromdb, todb, fromhost)   // copy database     
db.createCollection (name, {size: ..., capped: ..., max : ...}) // create table      
db.getCollectionNames () //  Get the table name of the current database       
db.printCollectionStats ()   // print the status information of each table     
db.printReplicationInfo ()   // print the replication status information of the master database     
db.printSlaveReplicationInfo ()   // print the replication status information 
db from the database     . removeUser (username) // Delete database user     
db.repairDatabase () // Repair database     
db.version () // Version number // Table operation 
db.test. count () // Number of rows in statistical table     
db.test.dataSize () // Statistic table data size        
db.test.dropIndex (name)   // Delete the specified index     
db.test.dropIndexes () // Delete all indexes     
db.test.ensureIndex (keypattern, Options)   // increase in the index   // View Help - library operation - Copy 
db.help () 

    db.adminCommand (nameOrDocument) - Switches to  ' ADMIN ' db, and runs the Command [ the 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   

 

Guess you like

Origin www.cnblogs.com/leiting/p/12682642.html