2. Mongo Shell

1. Mongo shell 简介

Mongo shell 是与MongoDB进行交互的 JavaScript接口,Mongo shell既可以对MongoDB进行CRUD(增删改查)操作,也可以执行对MongoDB的管理操作,如关闭MongoDB数据库等。

1.1 启动Mongo shell
  1. 进入MongDB安装目录(确保MongoDB服务进程已开启):

    cd <mongodb installation dir>
    
  2. 输入如下命令:

    ./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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,529评论 5 475
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,015评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,409评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,385评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,387评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,466评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,880评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,528评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,727评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,528评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,602评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,302评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,873评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,890评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,132评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,777评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,310评论 2 342

推荐阅读更多精彩内容

  • 搭建note 1 --初始环境,启动容器 在服务器家目录拉取mynote代码: git clone git@git...
    ronnyjiang阅读 821评论 0 0
  • 背景: 阅读新闻 12C CDB模式下RMAN备份与恢复 [日期:2016-11-29] 来源:Linux社区 作...
    阳屯okyepd阅读 3,331评论 0 7
  • mogon简介 MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可...
    猪哥亮阅读 1,990评论 0 10
  • 有一日 沉默填补了所有的问 广袤的死寂 犹如 断流的河 恢宏的骨架 它穿过繁茂的记忆 像一把森森的剑 像一道惨白的...
    藏雨的树洞阅读 323评论 0 3
  • 之一 本人身材矮小粗壮,面部丰满而不臃肿。性情嘛,半开朗半忧郁,合乎多血质与激动之间。“双腿、前胸,满布浓毛,”身...
    简书茶馆叶老板阅读 2,566评论 2 14