MongoDB 基础系列十二:mongo Shell 帮助

前言

此篇博文是 Mongdb 基础系列之一;

本文为作者的原创作品,转载需注明出处;

Command Line Help

1
$ mongo --help

将打印出如下的信息,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
MongoDB shell version v3.4.6
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
Options:
--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
--port arg port to connect to
--host arg server to connect to
--eval arg evaluate javascript
-h [ --help ] show this usage information
--version show version information
--verbose increase verbosity
--ipv6 enable IPv6 support (disabled by default)
--disableJavaScriptJIT disable the Javascript Just In Time
compiler
--disableJavaScriptProtection allow automatic JavaScript function
marshalling
--ssl use SSL for all connections
......

Shell Help

在 mongo shell 中输入如下指令,

1
> help

将输出如下的信息,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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

Database Help

在 mongo shell 中通过如下指令获得有关 Database 的帮助信息,

  • 获得当前所有 available 的 databases

    1
    > show dbs

    New in version 2.4: show databases is now an alias for show dbs

  • To see the list of help for methods you can use on the db object, call the db.help() method:

    1
    > db.help()

    将会所有相关的 db 方法集

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    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.eval() - deprecated
    ......
  • To see the implementation of a method in the shell, type the db.<method name> without the parenthesis (()), as in the following example which will return the implementation of the method db.updateUser():

    1
    > db.updateUser

    将返回 updateUser() 的具体实现;

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    function (name, updateObject, writeConcern) {
    var cmdObj = {updateUser: name};
    cmdObj = Object.extend(cmdObj, updateObject);
    cmdObj['writeConcern'] = writeConcern ? writeConcern : _defaultWriteConcern;
    this._modifyCommandToDigestPasswordIfNecessary(cmdObj, name);

    var res = this.runCommand(cmdObj);
    if (res.ok) {
    return;
    }

    if (res.errmsg == "no such cmd: updateUser") {
    this._updateUserV1(name, updateObject, cmdObj['writeConcern']);
    return;
    }

    throw _getErrorWithCode(res, "Updating user failed: " + res.errmsg);
    }

Collection Help

在 mongo shell 中执行,

  • 查看当前 database 中所有的 collections

    1
    > show collections

    在我本地的测试如下,

    1
    2
    3
    4
    5
    > use local
    switched to db local
    > show collections
    startup_log
    >
  • 查看某一个 collection 上的可用方法,直接在该 collection 上调用 help()

    1
    > db.collection.help()

    在我本地的测试如下,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    > db.startup_log.help()
    DBCollection help
    db.startup_log.find().help() - show DBCursor help
    db.startup_log.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j
    db.startup_log.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
    db.startup_log.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
    db.startup_log.convertToCapped(maxBytes) - calls {convertToCapped:'startup_log', size:maxBytes}} command
    db.startup_log.createIndex(keypattern[,options])
    db.startup_log.createIndexes([keypatterns], <options>)
    db.startup_log.dataSize()
  • 查看某一个 collection 对应的方法的实现,使用 db.<collection>.<method> name without the parenthesis (())

    1
    > db.collection.save

    在我本地的测试如下,

    1
    2
    3
    4
    > db.startup_log.dataSize
    function () {
    return this.stats().size;
    }

Cursor Help

When you perform read operations with the find() method in the mongo shell, you can use various cursor methods to modify the find() behavior and various JavaScript methods to handle the cursor returned from the find() method.

在执行读取操作的时候,你可以使用多种多样的 cursor 方法来修改 find() 方法的行为以及处理 find() 方法的返回方式;

  • To list the available modifier and cursor handling methods, use the db.collection.find().help() command

    1
    > db.collection.find().help()

    在我本地的测试如下,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    > db.startup_log.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
  • To see the implementation of the cursor method, type the db.<collection>.find().<method> name without the parenthesis (()), as in the following example which will return the implementation of the toArray() method:

    1
    > db.collection.find().toArray

Some useful methods for handling cursors are:

  • hasNext() which checks whether the cursor has more documents to return.
  • next() which returns the next document and advances the cursor position forward by one.
  • forEach() which iterates the whole cursor and applies the <function> to each document returned by the cursor. The <function> expects a single argument which corresponds to the document from each iteration.

For examples on iterating a cursor and retrieving the documents from the cursor, see cursor handling. See also Cursor for all available cursor methods.

Wrapper Object Help

通过 help misc 在 mongo shell 中查询得到所有可用的对象( wrapped class );

1
> help misc

返回

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
b = new BinData(subtype,base64str)  create a BSON BinData value
b.subtype() the BinData subtype (0..255)
b.length() length of the BinData data in bytes
b.hex() the data as a hex encoded string
b.base64() the data as a base 64 encoded string
b.toString()

b = HexData(subtype,hexstr) create a BSON BinData value from a hex string
b = UUID(hexstr) create a BSON BinData value of UUID subtype
b = MD5(hexstr) create a BSON BinData value of MD5 subtype
"hexstr" string, sequence of hex characters (no 0x prefix)

o = new ObjectId() create a new ObjectId
o.getTimestamp() return timestamp derived from first 32 bits of the OID
o.isObjectId
o.toString()
o.equals(otherid)

d = ISODate() like Date() but behaves more intuitively when used
d = ISODate('YYYY-MM-DD hh:mm:ss') without an explicit "new " prefix on construction

可见,返回的都是 mongo shell 中内置的可用的 Classes 对象,以及相关的调用方法;

References

https://docs.mongodb.com/manual/tutorial/access-mongo-shell-help/