1. Mongo shell 简介
Mongo shell 是与MongoDB进行交互的 JavaScript接口,Mongo shell既可以对MongoDB进行CRUD(增删改查)操作,也可以执行对MongoDB的管理操作,如关闭MongoDB数据库等。
1.1 启动Mongo shell
-
进入MongDB安装目录(确保MongoDB服务进程已开启):
cd <mongodb installation dir>
-
输入如下命令:
./bin/mongo
运行示例:
[xinhuan@MacBook-Pro] ~$ cd /usr/local/Cellar/mongodb/3.4.7/
[xinhuan@MacBook-Pro] 3.4.7$ ./bin/mongo
MongoDB shell version v3.4.7
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.7
Server has startup warnings:
2017-09-05T23:05:49.851+0800 I CONTROL [initandlisten]
2017-09-05T23:05:49.851+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-09-05T23:05:49.851+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2017-09-05T23:05:49.851+0800 I CONTROL [initandlisten]
2017-09-05T23:05:49.851+0800 I CONTROL [initandlisten]
2017-09-05T23:05:49.851+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
2. Mongo shell 操作
2.1 db
— 查看当前正在使用的数据库
db
运行示例如下,test数据库是默认数据库
> db
test
2.2 use
— 切换数据库
use <databa>
切换到MyCollection
数据库,如过MyCollection
不存在,则会自动创建
> use MyCollection
switched to db MyCollection
2.3 help
— Mongo shell 帮助命令
help
在 Mongo shell 中输入help
> 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
2.4 show
— 查询相关信息
-
show dbs
或者show databases
— 查看数据库> show dbs admin 0.000GB local 0.000GB
-
show collections
— 查看当前数据库中的集合(collection)> use admin switched to db admin > show collections system.version
> use local switched to db local > show collections startup_log
-
show log [name]
— 查看日志,name
的默认值为gloable
> show log 2017-09-05T23:05:49.291+0800 I CONTROL [initandlisten] MongoDB starting : pid=948 port=27017 dbpath=/usr/local/var/mongodb 64-bit host=MacBook-Pro.local 2017-09-05T23:05:49.291+0800 I CONTROL [initandlisten] db version v3.4.7 2017-09-05T23:05:49.291+0800 I CONTROL [initandlisten] git version: cf38c1b8a0a8dca4a11737581beafef4fe120bcd 2017-09-05T23:05:49.291+0800 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.2l 25 May 2017 2017-09-05T23:05:49.291+0800 I CONTROL [initandlisten] allocator: system 2017-09-05T23:05:49.291+0800 I CONTROL [initandlisten] build environment: 2017-09-05T23:05:49.291+0800 I CONTROL [initandlisten] distarch: x86_64 2017-09-05T23:05:49.291+0800 I CONTROL [initandlisten] target_arch: x86_64 2017-09-05T23:05:49.291+0800 I CONTROL [initandlisten] options: { config: "/usr/local/etc/mongod.conf", net: { bindIp: "127.0.0.1" }, storage: { dbPath: "/usr/local/var/mongodb" }, systemLog: { destination: "file", logAppend: true, path: "/usr/local/var/log/mongodb/mongo.log" } } 2017-09-05T23:05:49.292+0800 I - [initandlisten] Detected data files in /usr/local/var/mongodb created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'. 2017-09-05T23:05:49.292+0800 I STORAGE [initandlisten] wiredtiger_open config: create,cache_size=3584M,session_max=20000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0), 2017-09-05T23:05:49.877+0800 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory '/usr/local/var/mongodb/diagnostic.data' 2017-09-05T23:05:49.878+0800 I NETWORK [thread1] waiting for connections on port 27017 2017-09-05T23:08:13.532+0800 I NETWORK [thread1] connection accepted from 127.0.0.1:51118 #1 (1 connection now open) 2017-09-05T23:08:13.533+0800 I NETWORK [conn1] received client metadata from 127.0.0.1:51118 conn1: { application: { name: "MongoDB Shell" }, driver: { name: "MongoDB Internal Client", version: "3.4.7" }, os: { type: "Darwin", name: "Mac OS X", architecture: "x86_64", version: "16.7.0" } }
2.5 db.help()
— 数据库帮助
> 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.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
2.6 db.collection.help()
— 集合帮助
> db.collection.help()
DBCollection help
db.collection.find().help() - show DBCursor help
db.collection.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j
db.collection.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
db.collection.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
db.collection.convertToCapped(maxBytes) - calls {convertToCapped:'collection', size:maxBytes}} command
db.collection.createIndex(keypattern[,options])
db.collection.createIndexes([keypatterns], <options>)
db.collection.dataSize()
db.collection.deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j
db.collection.deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j
db.collection.distinct( key, query, <optional params> ) - e.g. db.collection.distinct( 'x' ), optional parameters are: maxTimeMS
db.collection.drop() drop the collection
db.collection.dropIndexes()
db.collection.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead
db.collection.explain().help() - show explain help
db.collection.reIndex()
db.collection.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
e.g. db.collection.find( {x:77} , {name:1, x:1} )
db.collection.find(...).count()
db.collection.find(...).limit(n)
db.collection.find(...).skip(n)
db.collection.find(...).sort(...)
db.collection.findOne([query], [fields], [options], [readConcern])
db.collection.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
db.collection.insert(obj)
db.collection.insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j
db.collection.insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j
db.collection.mapReduce( mapFunction , reduceFunction , <optional params> )
db.collection.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor
db.collection.remove(query)
db.collection.replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j
db.collection.renameCollection( newName , <dropTarget> ) renames the collection.
db.collection.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
db.collection.save(obj)
...
2.7 db.<collection>.find().<method>
— 游标(cursor)帮助
> db.collection.find().help()
find(<predicate>, <projection>) modifiers
.sort({...})
.limit(<n>)
.skip(<n>)
.batchSize(<n>) - sets the number of docs to return per getMore
.collation({...})
.hint({...})
.readConcern(<level>)
.readPref(<mode>, <tagset>)
.count(<applySkipLimit>) - total # of objects matching query. by default ignores skip,limit
.size() - total # of objects cursor would return, honors skip,limit
.explain(<verbosity>) - accepted verbosities are {'queryPlanner', 'executionStats', 'allPlansExecution'}
.min({...})
.max({...})
.maxScan(<n>)
.maxTimeMS(<n>)
.comment(<comment>)
.snapshot()
.tailable(<isAwaitData>)
.noCursorTimeout()
.allowPartialResults()
.returnKey()
.showRecordId() - adds a $recordId field to each returned object
Cursor methods
.toArray() - iterates through docs and returns an array of the results
.forEach(<func>)
.map(<func>)
.hasNext()
.next()
.close()
.objsLeftInBatch() - returns count of docs left in current batch (when exhausted, a new getMore will be issued)
.itcount() - iterates through documents and counts them
.getQueryPlan() - get query plans associated with shape. To get more info on query plans, call getQueryPlan().help().
.pretty() - pretty print each document, possibly over multiple lines