MongoDB学习笔记05-Shell常用命令

连接到一个 MongoDB

在命令行提示符下,输入 mongo 命令来启动 mongo 程序

C:\Users\bin>mongo
MongoDB shell version: 3.0.2
connecting to: test

shell命令基本使用

更多详见官方文档
mongo 程序启动时会默认选定 test 数据库。

操作数据库

> db  # 打印出当前的数据库名
> show dbs  # 列出所有数据库
> use db  # 切换到一个新的数据库 db

> db.dropDatabase()  # 删除当前数据库
> db.cloneDatabase("127.0.0.1")   # 将指定机器上的和当前数据库名相同的数据库的数据克隆到当前数据库,
> db.copyDatabase("mydb", "temp", "127.0.0.1")  # 将本机的mydb的数据复制到temp数据库中
> db.repairDatabase()  # 修复当前数据库

> db.getName()  # 查看当前使用的数据库,也可以直接用db
> db.stats()  # 显示当前db状态
> db.version()  # 当前db版本
> db.getMongo()  # 查看当前db的链接机器地址
> db.serverStatus()  # 查看数据库服务器的状态

操作集合

> show collections  # 查看某个数据库中所有的集合
> db.集合名.drop()  # 删除数据库中指定的集合
> db.集合名.help()

创建集合

createCollection() 方法的基本格式:db.createCollection(name, options)

在该命令中,name 是所要创建的集合名称。options 是一个用来指定集合配置的文档。

参数 类型 描述
name 字符串 所要创建的集合名称
options 文档 可选。指定有关内存大小及索引的选项

参数 options 是可选的,所以你必须指定的只有集合名称。下表列出了所有可用选项:

字段 类型 描述
capped 布尔 (可选)如果为 true,则创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。
当该值为 true 时,必须指定 size 参数。
autoIndexID 布尔 (可选)如为 true,自动在 _id 字段创建索引。默认为 false。
size 数值 (可选)为固定集合指定一个最大值(以字节计)。
如果 capped 为 true,也需要指定该字段。
max 数值 (可选)指定固定集合中包含文档的最大数量。

MongoDB自带一个JavaScript Shell

  它是一个JavaScript解释器,还是一个MongoDB的客户端,可以通过JavaScript与启动的数据库实例进行交互(Shell中命令区分大小写)。在Shell中,每当写完一句完整的JS代码,Shell就会将其结果返回。

shell中的help函数:

当进入到某个数据库中,要如何知道可以使用哪些操作呢?此时就可以使用help函数,如下图,就能够列出数据库级别有哪些用法了,当然除了数据库级别的help,还有集合级别的help,使用方法为:db.集合名.help()。在函数名称后面不添加()还可以查看函数的源码。

> db.help()
DB methods:
        db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs comma
nd [ 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.createUser(userDocument)
        db.currentOp() displays currently executing operations in the db
        db.dropDatabase()
        db.eval(func, args) run code server-side
        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()
        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, tu
rns 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 w
rites to the db
        db.unsetWriteConcern( <write concern doc> ) - unsets the write concern f
or 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.getName()
test
>
//查看函数源代码
> db.getName
function (){
    return this._name;
}
>

Shell内置的JS引擎可以直接执行执行JS代码

> function invokeEval(){
... return db.eval("return 123")
... }
> invokeEval()
123
>

connect()

虽然Shell中提供的全局变量db指向当前连接的数据库,但还可以用其它的变量来保存其它连接的数据库,利用Shell中提供的connect()命令即可,

> db
test
> var udb = connect("127.0.0.1:27017/admin")
connecting to: 127.0.0.1:27017/admin
> udb
admin
> db
test
>


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 bin07280@qq.com

文章标题:MongoDB学习笔记05-Shell常用命令

文章字数:1.3k

本文作者:Bin

发布时间:2017-07-17, 15:21:38

最后更新:2019-08-06, 00:07:35

原始链接:http://coolview.github.io/2017/07/17/MongoDB/MongoDB%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B005-Shell%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录