Share&Joy

Ginger' Blog


  • 首页
  • 归档
  • 标签
  •   

© 2018 1-riverfish

Theme Typography by Makito

Proudly published with Hexo

MongoDB学习笔记3

发布于 2017-09-25 MongoDB 数据库 

MongoDB学习笔记3

使用MongoDB shell

介绍如何将shell作为命令行工具的一部分来使用,如何对shell进行定制,以及shell的一些高级功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//可以将shell连接到任何MongoDB实例(前提你的计算机与MongoDB实例所在计算机能够连通)
$ mongo some-host:30000/myDB

//db现在就指向了some-hostt:30000上的myDB数据库

//启动mongo shell时不连接到任何mongod
jiang@jiang-ThinkPad-E450:~$ mongo --nodb
MongoDB shell version v3.4.9
> conn = new Mongo("jiang-ThinkPad-E450:27017")
connection to jiang-ThinkPad-E450:27017
> db = conn.getDB("test")
test

//任何时候都可以使用这些命令来连接到不同的数据库或服务器

1. shell小贴士

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//shell内置的帮助文档
> 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

//查询一个函数是做什么用的,可以直接在shell输入函名(函数名后不要加小括号),可以看到Js实现代码
> db.mycoll.update
function (query, obj, upsert, multi) {
var parsed = this._parseUpdate(query, obj, upsert, multi);
var query = parsed.query;
var obj = parsed.obj;
var upsert = parsed.upsert;
var multi = parsed.multi;
var wc = parsed.wc;
var collation = parsed.collation;

var result = undefined;
var startTime =
(typeof(_verboseShell) === 'undefined' || !_verboseShell) ? 0 : new Date().getTime();

if (this.getMongo().writeMode() != "legacy") {
var bulk = this.initializeOrderedBulkOp();
var updateOp = bulk.find(query);

if (upsert) {
updateOp = updateOp.upsert();
}

if (collation) {
updateOp.collation(collation);
}

if (multi) {
updateOp.update(obj);
} else {
updateOp.updateOne(obj);
}

try {
result = bulk.execute(wc).toSingleResult();
} catch (ex) {
if (ex instanceof BulkWriteError || ex instanceof WriteCommandError) {
result = ex.toSingleResult();
} else {
// Other exceptions thrown
throw Error(ex);
}
}
} else {
if (collation) {
throw new Error("collation requires use of write commands");
}

this._validateUpdateDoc(obj);
this.getMongo().update(this._fullName, query, obj, upsert, multi);

// Enforce write concern, if required
if (wc) {
result = this.runCommand("getLastError", wc instanceof WriteConcern ? wc.toJSON() : wc);
}
}

this._printExtraInfo("Updated", startTime);
return result;
}

2.使用shell执行脚本

shell可以将希望执行的Js文件传给shell

1
2
3
4
5
6
7
//mongo shell会依次执行传入的脚本,然后退出
$ mongo --quiet host-name:27017/test script1.js
//db指向host-name:27017的test数据库,然后执行脚本
//注意,选项要出现在地址之前,使用--quiet选项的命令,可以让shell不打印“MongoDBshellversionv3.4.9”

//也可以使用load()函数,从交互式shell中运行脚本
load("script1.js")

在脚本中可以访问db变量,以及其他全局变量。然额,shell辅助函数“use”,”show”不可以在文件中使用。这些辅助函数都有对应的JS函数。

辅助函数 等价函数
use foo db.getSisterDB(“foo”)
show dbs db.getMongo().getDBs()
show collections db.getCollectionNames()

默认情况下,shell会在运行shell时所处的目录中查找脚本(可以使用run(“pwd”)命令查看)。如果脚本不在当前目录,可以为shell指定一个相对路径或者绝对路径。

1
2
load("/home/jiang/my-scripts/defineConnectTo.js")
//注意,load函数无法解析 ~

可以在shell中使用run()函数来执行命令行程序,通常来说,这种使用方式局限性非常大,因为输出格式很怪,而且不支持管道。

1
run("ls","-l","/home/jiang/文档")

3.创建.mongorc.js文件

将频繁加载的脚本添加到mongorc.js文件中,这个文件会在启动shell时自动运行。在启动时指定 –norc参数,就可以禁止加载.mongorc.js。.mongorc.js最常见的用途之一是移除那些比较危险的shell辅助函数。可以在这里集中重写方法,或者为这些辅助函数添加no选项,或者取消他们的定义。

1
2
3
4
5
6
//例如,我们希望启动成功时让shell显示一句欢迎语,在用户主目录下创建一个名为.mongorc.js的文件
//mongorc.js
var compliment = ["handsome","lovely","like a good-man"];
var index = Math.floor(Math.random()*3);

print("Hello,you are looking particularly " + compliment[index] + " today!");
1
2
3
4
5
6
7
8
9
var no = function (){
print("Not on my watch.");
}
//禁止删除数据库
db.dropDatabase = DB.prototype.dropDatabase = no;
//禁止删除集合
DBCollection.prototype.drop = no;
//禁止删除索引
DBCollection.prototype.dropIndex = no;

4.定制shell提示

将prompt变量设为一个字符串或者函数,就可以重写默认的shell提示。

5.编辑复合变量

为了方便地调用编辑器,可以在shell中设置EDITOR变量

1
2
3
4
5
> RRDITOR ="bin/nano"

//现在,如果想要编辑一个变量,可以使用 edit 变量名
//修改完成后,保存并退出编辑器,变量就会被重新解析然后加载回shell
//.mongorc.js中添加一行 RRDITOR ="bin/emacs",以后就不必单独设置了

6.集合命名注意事项

访问无效属性名称命名的集合

1
2
3
4
5
//法一  函数
db.getCollection("name");

//法二 数组访问语法
x.y等同于x["y"]

Any question please contact 1-riverfish

分享到 

 上一篇: MongoDB学习笔记4 下一篇: MongoDB学习笔记2 

© 2018 1-riverfish

Theme Typography by Makito

Proudly published with Hexo