一、mongo基础用法
MongoDB中自带JavaScript shell,可以在shell中使用命令行与MongoDB实例进行交互,在保证MongoDB实例启动的情况下(可以参见MongoDB单机的安装与启动),在bin目录下的mongo进行启动,
1、默认会链接到test数据库:
2、若想链接到远程的某一mongoDB实例,则:./mongo ip:port/数据库名称 (即默认为 ./mongo 127.0.0.1:27017/test )
3、若不想链接到任何的数据库时(在设置副本集等会使用到),则可以使用 --nodb 命令
4、若需要链接到数据库实例,再获取数据库则可以(即:./mongo ip:port/数据库名 的一个分解步骤):
5、shell是一个JavaScript,可以进行简单的数学运算;可以使用JavaScript的标准库;可以定义和调用函数,如下:
6、mongo的更多命令可以使用db.help()命令进行查找,数据库级别的命令可以使用db.数据库名称.help()进行查找,如下:
> db.help()
DB methods:
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)
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
> db.test.help()
DBCollection help
db.test.find().help() - show DBCursor help
db.test.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j
db.test.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
db.test.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
db.test.convertToCapped(maxBytes) - calls {convertToCapped:'test', size:maxBytes}} command
db.test.createIndex(keypattern[,options])
db.test.createIndexes([keypatterns], <options>)
db.test.dataSize()
db.test.deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j
db.test.deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j
db.test.distinct( key, query, <optional params> ) - e.g. db.test.distinct( 'x' ), optional parameters are: maxTimeMS
db.test.drop() drop the collection
db.test.dropIndex(index) - e.g. db.test.dropIndex( "indexName" ) or db.test.dropIndex( { "indexKey" : 1 } )
db.test.dropIndexes()
db.test.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead
db.test.explain().help() - show explain help
db.test.reIndex()
db.test.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
e.g. db.test.find( {x:77} , {name:1, x:1} )
db.test.find(...).count()
db.test.find(...).limit(n)
db.test.find(...).skip(n)
db.test.find(...).sort(...)
db.test.findOne([query], [fields], [options], [readConcern])
db.test.findOneAndDelete( filter, <optional params> ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS
db.test.findOneAndReplace( filter, replacement, <optional params> ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
db.test.findOneAndUpdate( filter, update, <optional params> ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
db.test.getDB() get DB object associated with collection
db.test.getPlanCache() get query plan cache associated with collection
db.test.getIndexes()
db.test.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
db.test.insert(obj)
db.test.insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j
db.test.insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j
db.test.mapReduce( mapFunction , reduceFunction , <optional params> )
db.test.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor
db.test.remove(query)
db.test.replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j
db.test.renameCollection( newName , <dropTarget> ) renames the collection.
db.test.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
db.test.save(obj)
db.test.stats({scale: N, indexDetails: true/false, indexDetailsKey: <index key>, indexDetailsName: <index name>})
db.test.storageSize() - includes free space allocated to this collection
db.test.totalIndexSize() - size in bytes of all the indexes
db.test.totalSize() - storage allocated for all data and indexes
db.test.update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi
db.test.updateOne( filter, update, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j
db.test.updateMany( filter, update, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j
db.test.validate( <full> ) - SLOW
db.test.getShardVersion() - only for use with sharding
db.test.getShardDistribution() - prints statistics about data distribution in the cluster
db.test.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function
db.test.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
db.test.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection
db.test.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection
db.test.latencyStats() - display operation latency histograms for this collection
二、使用shell执行脚本
若想要执行的shell比较长,则可以不仅仅像上面一样在命令行中编写,可以在写好的js文件(路径名加文件名即可)中直接执行,多个文件中间用空间间隔; 若需要在远程实例上执行该shell的文件,则
./mongo --quiet ip:port/数据库名 shell-file-1.js shell-file-2.js shell-file-3.js
三、创建 .mongorc.js 文件
若某些脚本会被经常加载或者欢迎语,则需要将其添加到用户主目录下的 .mongorc.js 中(没有就创建一个),与之前的在shell的用户目录下修改.bashrc实现佛主保佑,永无bug 是一样的。但是主要用途在于可以添加一些禁止删除数据或者索引的语句,这个是运维的比较不错的选择。
var no = function(operate){
print("不允许删除" + operate + "操作,请联系运维相关人员!!!");
}
// 禁止删除数据库的操作
db.dropDatabase = DB.prototype.dropDatabase = no("数据库");
// 禁止删除集合操作
DBCollection.prototype.drop = no("集合");
// 禁止删除
DBCollection.prototype.dropIndex = no("索引");
若在启动shell的时候,使用 --norc参数,则不会加载 .mongorc.js 文件。