mongo shell简介

备注:
MongoDB 4.2 版本

一.mongo shell连接MongoDB

-- mongo shell连接本机MongoDB
mongo
-- mongo shell通过端口号连接本机MongoDB
mongo --port 27017
-- mongo shell通过ip及端口号连接MongoDB
mongo --host mongodb0.example.com --port 28015
eg:
mongo --host 10.31.1.124 --port 27017
mongo --host 10.31.1.124:27017

--username   (用户名)
--password     (密码)
--authenticationDatabase  (认证数据库)

测试记录:

[root@10-31-1-124 mongodb]# mongo
MongoDB shell version v4.2.10
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("8230936a-78e2-4c50-88a8-8adc43b8e83c") }
MongoDB server version: 4.2.10
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
        https://community.mongodb.com
Server has startup warnings: 
2020-11-05T15:33:01.738+0800 I  CONTROL  [initandlisten] 
2020-11-05T15:33:01.738+0800 I  CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2020-11-05T15:33:01.738+0800 I  CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2020-11-05T15:33:01.738+0800 I  CONTROL  [initandlisten] 
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] 
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] 
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] 
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

> 

[root@10-31-1-124 mongodb]# mongo --port 27017
MongoDB shell version v4.2.10
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("56b04cfe-dfcb-4985-acb9-5fec408d0dde") }
MongoDB server version: 4.2.10
Server has startup warnings: 
2020-11-05T15:33:01.738+0800 I  CONTROL  [initandlisten] 
2020-11-05T15:33:01.738+0800 I  CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2020-11-05T15:33:01.738+0800 I  CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2020-11-05T15:33:01.738+0800 I  CONTROL  [initandlisten] 
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] 
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] 
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2020-11-05T15:33:01.739+0800 I  CONTROL  [initandlisten] 
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

> 

[root@10-31-1-124 ~]# mongo --host 10.31.1.124 --port 27017
MongoDB shell version v4.2.10
connecting to: mongodb://10.31.1.124:27017/?compressors=disabled&gssapiServiceName=mongodb
2020-11-05T16:02:33.881+0800 E  QUERY    [js] Error: couldn't connect to server 10.31.1.124:27017, connection attempt failed: SocketException: Error connecting to 10.31.1.124:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:353:17
@(connect):2:6
2020-11-05T16:02:33.883+0800 F  -        [main] exception: connect failed
2020-11-05T16:02:33.883+0800 E  -        [main] exiting with code 1
[root@10-31-1-124 ~]# 

发现通过IP连接的发生了错误
原因是绑定的Ip地址的问题,默认是127.0.0.1,多个IP地址用逗号分隔
修改配置文件:

# network interfaces
net:
  port: 27017
  bindIp: 10.31.1.124,127.0.0.1  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.

重新测试,发现无问题

[root@10-31-1-124 ~]# mongo --host 10.31.1.124 --port 27017
MongoDB shell version v4.2.10
connecting to: mongodb://10.31.1.124:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("06e9c28b-cbb5-4dc0-9fdd-d2801665454d") }
MongoDB server version: 4.2.10
Server has startup warnings: 
2020-11-05T16:07:09.344+0800 I  CONTROL  [initandlisten] 
2020-11-05T16:07:09.344+0800 I  CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2020-11-05T16:07:09.344+0800 I  CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2020-11-05T16:07:09.344+0800 I  CONTROL  [initandlisten] 
2020-11-05T16:07:09.344+0800 I  CONTROL  [initandlisten] 
2020-11-05T16:07:09.344+0800 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2020-11-05T16:07:09.344+0800 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2020-11-05T16:07:09.344+0800 I  CONTROL  [initandlisten] 
2020-11-05T16:07:09.344+0800 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2020-11-05T16:07:09.344+0800 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2020-11-05T16:07:09.344+0800 I  CONTROL  [initandlisten] 
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

二.配置mongo shell

还有一些其它配置,目前看这个配置比较有用,先使用这个

自定义提示以显示数据库和主机名

host = db.serverStatus().host;

prompt = function() {
             return db+"@"+host+"$ ";
         }

测试记录:

> host = db.serverStatus().host;
10-31-1-124
> prompt = function() {
...              return db+"@"+host+"$ ";
...          }
function() {
             return db+"@"+host+"$ ";
         }
test@10-31-1-124$ 
test@10-31-1-124$ 

三.使用 mongo Shell帮助

-- 命令行帮助
mongo --help
-- shell 帮助
help
-- 数据库帮助
show dbs
db.help()
-- 表级别的帮助
show collections 
db.collections.help()
db.collection.save

测试记录:

[root@10-31-1-124 ~]# mongo --help
MongoDB shell version v4.2.10
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
  foo                   foo database on local machine
  192.168.0.5/foo       foo database on 192.168.0.5 machine
  192.168.0.5:9999/foo  foo database on 192.168.0.5 machine on port 9999
  mongodb://192.168.0.5:9999/foo  connection string URI can also be used
Options:
  --ipv6                               enable IPv6 support (disabled by 
                                       default)
  --host arg                           server to connect to
  --port arg                           port to connect to
  -h [ --help ]                        show this usage information
  --version                            show version information
  --verbose                            increase verbosity
  --shell                              run the shell after executing files
  --nodb                               don't connect to mongod on startup - no 
                                       'db address' arg expected
  --norc                               will not run the ".mongorc.js" file on 
                                       start up
  --quiet                              be less chatty
  --eval arg                           evaluate javascript
  --disableJavaScriptJIT               disable the Javascript Just In Time 
                                       compiler
  --enableJavaScriptJIT                enable the Javascript Just In Time 
                                       compiler
  --disableJavaScriptProtection        allow automatic JavaScript function 
                                       marshalling
  --retryWrites                        automatically retry write operations 
                                       upon transient network errors
  --disableImplicitSessions            do not automatically create and use 
                                       implicit sessions
  --jsHeapLimitMB arg                  set the js scope's heap size limit

Authentication Options:
  -u [ --username ] arg                username for authentication
  -p [ --password ] arg                password for authentication
  --authenticationDatabase arg         user source (defaults to dbname)
  --authenticationMechanism arg        authentication mechanism
  --gssapiServiceName arg (=mongodb)   Service name to use when authenticating 
                                       using GSSAPI/Kerberos
  --gssapiHostName arg                 Remote host name to use for purpose of 
                                       GSSAPI/Kerberos authentication

FLE AWS Options:
  --awsAccessKeyId arg                 AWS Access Key for FLE Amazon KMS
  --awsSecretAccessKey arg             AWS Secret Key for FLE Amazon KMS
  --awsSessionToken arg                Optional AWS Session Token ID
  --keyVaultNamespace arg              database.collection to store encrypted 
                                       FLE parameters
  --kmsURL arg                         Test parameter to override the URL for 
                                       KMS

TLS Options:
  --tls                                use TLS for all connections
  --tlsCertificateKeyFile arg          PEM certificate/key file for TLS
  --tlsCertificateKeyFilePassword arg  Password for key in PEM file for TLS
  --tlsCAFile arg                      Certificate Authority file for TLS
  --tlsCRLFile arg                     Certificate Revocation List file for TLS
  --tlsAllowInvalidHostnames           Allow connections to servers with 
                                       non-matching hostnames
  --tlsAllowInvalidCertificates        Allow connections to servers with 
                                       invalid certificates
  --tlsFIPSMode                        Activate FIPS 140-2 mode at startup
  --tlsDisabledProtocols arg           Comma separated list of TLS protocols to
                                       disable [TLS1_0,TLS1_1,TLS1_2]

file names: a list of files to run. files have to end in .js and will exit after unless --shell is specified
[root@10-31-1-124 ~]# 


> 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
> 

> 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) - will only function with MongoDB 4.0 and below
        db.commandHelp(name) returns the help for the command
        db.copyDatabase(fromdb, todb, fromhost) - will only function with MongoDB 4.0 and below
        db.createCollection(name, {size: ..., capped: ..., max: ...})
        db.createUser(userDocument)
        db.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions})
        db.currentOp() displays currently executing operations in the db
        db.dropDatabase(writeConcern)
        db.dropUser(username)
        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().setSecondaryOk() allow queries on a replication secondary server
        db.getName()
        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.hello() 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.printSecondaryReplicationInfo()
        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.setVerboseShell(flag) display extra information in shell output
        db.setWriteConcern(<write concern doc>) - sets the write concern for writes to the db
        db.shutdownServer()
        db.stats()
        db.unsetWriteConcern(<write concern doc>) - unsets the write concern for writes to the db
        db.version() current version of the server
        db.watch() - opens a change stream cursor for a database to report on all  changes to its non-system collections.
> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值