Contenu connexe Similaire à Mongo db introduction Similaire à Mongo db introduction (20) Mongo db introduction2. 内容
• 简介
• 安装
• 启动、停止
• 插入、删除、更新、查找
• 聚合、Map-Reduce、索引
• 高级主题:复制、分片
• 管理
3. 内容
• 简介
• 安装
• 启动、停止
• 插入、删除、更新、查找
• 聚合、Map-Reduce、索引
• 高级主题:复制、分片
• 管理
7. • Document-Oriented Storage
• Full Index Support
• Replication & High Availability
• Auto-Sharding
• Rich, document-based queries.
• Atomic modifiers for contention-
free performance.
• Map/Reduce
• ……
10. 内容
• 简介
• 安装
• 启动、停止
• 插入、删除、更新、查找
• 聚合、Map-Reduce、索引
• 高级主题:复制、分片
• 管理
12. • Linux Binary 安装:
–wget http://fastdl.mongodb.org/linux/mongodb-
linux-x86_64-2.4.1.tgz
–tar zxvf mongodb-linux-x86_64-2.4.1.tgz
–mv mongodb-linux-x86_64-2.4.1 mongodb
–cd mongodb:
–cd bin:
14. 内容
• 简介
• 安装
• 启动、停止
• 插入、删除、更新、查找
• 聚合、Map-Reduce、索引
• 高级主题:复制、分片
• 管理
15. • mongod
–mongodb的主进程,启动时支持众多参数,
• --config <filename>
• --port <port>
• --fork
• ……
• 示例:
mongod --port 27017 --fork –logpath
/srv/mongodb/mongodb.log --dbpath /srv/mongodb/
• 详细参数:
http://docs.mongodb.org/manual/reference/mongod/
16. • Stop mongodb:
–./mongo --host xxx --port yyy 登陆;
–然后运行:
• use admin;
• db.shutdownServer();
–也可以找到 mongod 进程,kill -2 PID
18. • > show dbs
admin (empty)
local 25.94140625GB
test 29.939453125GB
• > use test
switched to db test
• > show collections
system.indexes
test0
test1
test2
20. • >use test
• >db.test_0.insert({name:"qfdai2"})
• > db.test_0.find()
{ "_id" :
ObjectId("5178e9372ae21fe1fb129a32"),
"name" : "qfdai2" }
• > db.test_0.count()
1
23. 内容
• 简介
• 安装
• 启动、停止
• 插入、删除、更新、查找
• 聚合、Map-Reduce、索引
• 高级主题:复制、分片
• 管理
25. • 插入
db = Connection(host="192.168.86.14", port=27017).test
mycollection = db.test_0
mycollection.insert({"color":"red", "size":100})
mycollection.insert({"color":"green", "size":120})
mycollection.insert({"color":"blue", "size":110})
mycollection.insert({"color":"purple", "size":140})
mycollection.insert({"color":"orange", "size":150})
mycollection.insert({"color":"yellow", "size":90})
• 批量插入更有效(批量插入数-消耗时间)
26. SQL: DELETE FROM tbl_name [WHERE
where_definition] [ORDER BY
...] [LIMIT row_count]
DROP TABLE tbl_name;
28. SQL: UPDATE tbl_name SET
col_name1=expr1 [,
col_name2=expr2 ...] [WHERE
where_definition] [ORDER BY
...] [LIMIT row_count]
29. • 更新
db.collection.update( <query>, <update>, <options> )
<query>:对应 where 语句;
<update>:对应 SET语句;
默认的更新只更新一个,如果更新多个,需要添加 options。
MongoDB single update:
– mycollection.insert({"color":"yellow", "size":90})
– mycollection.insert({"color":"yellow", "size":30})
– mycollection.update({"color":"yellow"}, {"$set": {"size":120}})
结果
30. • 更新
MongoDB multi update:
– mycollection.insert({"color":"yellow", "size":90})
– mycollection.insert({"color":"yellow", "size":30})
– mycollection.update({"color":"yellow"}, {"$set": {"size":120}},
multi=True)
MongoDB upsert: 如果没找到满足条件的,则插入
– mycollection.update({"color":"zzz"}, {"$set": {"size":120}},
upsert=True)
结果
结果
31. • 更新—更多的修改器
• 操作字段
– $inc, $rename,$set,$setOnInsert,$unset
• 操作数组
– $addToSet,$pop,$pullAll,$pull,$pushAll,
– $push,$each,$slice,$sort
32. 更新—操作字段
$inc:对某个字段增加值
– mycollection.insert({"color":"yellow", "size":90})
– mycollection.insert({"color":"blue", "size":30})
– mycollection.update({"color":"blue"}, {"$inc":{"size":40}})
$unset:删除某个字段
– mycollection.insert({"color":"blue", "size":30})
– mycollection.update({"color":"blue"}, {"$unset":{"color":1}})
结果
结果
34. 更新—操作数组
$addToSet:将某个值放到数组中,仅当数组中不存在才放入。
– mycollection.insert({"color":"blue", "myset":['a','c','b']})
– mycollection.update({"color":"blue"}, {"$addToSet":{"myset":'a'}})
– mycollection.update({"color":"blue"}, {"$addToSet":{"myset":'b'}})
– mycollection.update({"color":"blue"}, {"$addToSet":{"myset":'e'}})
加入多个
– mycollection.insert({"color":"blue", "myset":['a','c','b']})
– mycollection.update({"color":"blue"}, {"$addToSet":{"myset": {"$each":
['e','b','f']}}})
{
"_id" : ObjectId("5179e19b8a267c22d8f30b9d"),
"color" : "blue",
"myset" : ["a", "c", "b", "e"]
}
{
"_id" : ObjectId("5179e27b8a267c2df8e68615"),
"color" : "blue",
"myset" : ["a", "c", "b", "e", "f"]
}
结果
结果
35. 更新—操作数组
$pop:删除数组中最后或第一个元素
– mycollection.insert({"color":"blue", "myset":['a','c','b']})
– mycollection.update({"color":"blue"}, {"$pop":{"myset": 1}})
#remove last
– mycollection.update({"color":"blue"}, {"$pop":{"myset": -1}})
#remove first
$pullAll,$pull:从数组中删除值
– mycollection.insert({"color":"blue",
"myset":['a','c','b','b','e']})
– mycollection.update({"color":"blue"}, {"$pull":{"myset": 'b'}})
– mycollection.update({"color":"blue"}, {"$pullAll":{"myset":
['a','c']}}) {
"_id" :
ObjectId("5179e4f08a267c22d878e0a5"),
"color" : "blue",
"myset" : ["e"]
}
结果
36. 更新—操作数组
$psuh, $pushAll:向数组添加元素
– mycollection.insert({"color":"blue"})
– mycollection.update({"color":"blue"}, {"$push":{"myset": 'b'}})
– mycollection.update({"color":"blue"}, {"$pushAll":{"myset":
['a','c']}})
– mycollection.update({“color”:“blue”},
{“$push”:{“myset”: {“$each”: [‘g’,‘b’,‘f’]}}}) #使
用 each
{
"_id" :
ObjectId("5179e83b8a267c378c7660c6"),
"color" : "blue",
"myset" : ["b", "a", "c", "g", "b", "f"]
}
结果
37. 更新—操作数组
$slice:与$each 一起使用,为0或负数,截取 后几位
– mycollection.insert({"color":"blue", "size":[11,22]})
– mycollection.update({"color":"blue"}, {"$push":{"size":
{"$each":[1,3,4,5,6], "$slice":-2}}})
$sort:对数组中元素排序,数组中元素必须是document
– mycollection.insert({“color”:“blue”,
“size”:[{“socre”:10,“name”:“aaa”},
{“score”:20,“name”:“bbb”}]})
– mycollection.update({"color":"blue"}, {"$push":{"size": {"$each":
[{"score":50,"name":"ccc"}, {"score":30,"name":"ddd“}], “$slice":-
3"$sort":{"score":1}}}})
{
"_id" : ObjectId("5179f5e88a267c4308024d93"),
"color" : "blue“, "size" : [5, 6]
}
{"_id" : ObjectId("5179f8178a267c4380bd8375"),"color" : "blue",
"size" : [{"score" : 20,"name" : "bbb"}, {"score" : 30,"name" : "ddd"},
{"score" : 50,"name" : "ccc"}]}
结果
结果
39. • 查找
db.collection.find( <query>, <projection> )
<query>:对应于 WHERE statement
<projection>:对应于需要从结果里面检索出来的字段
db.collection.find(): 返回集合中所有的文档。
插入数据:
–mycollection.insert({"_id":1, "name":"aaa", "age":20})
–mycollection.insert({"_id":2, "name":"bbb", "age":65})
–mycollection.insert({"_id":3, "name":"ccc", "age":54})
–mycollection.insert({"_id":4, "name":"ddd", "age":39})
–mycollection.insert({"_id":5, "name":"eee", "age":2})
–mycollection.insert({"_id":6, "name":"fff", "age":70})
41. 查找—数组
db.collection.find({field:value}):返回field数组中匹配value
的文档:
mycollection.insert({"_id":1, "name":["a","b","c"], "age":20})
mycollection.insert({"_id":1, "name":["e","f"], "age":30})
mycollection.find({"name": "e"})
数组中元素为文档:一般使用$elemMatch
– mycollection.insert({"_id":1, "name":[{"a": "a11", "b": "b11"}, {"a":
"a12", "b": "b12"}], "age":20})
– mycollection.insert({"_id":2, "name":[{"a": "a21", "b": "b21"}],
"age":30})
mycollection.find({“name.a”: “a11”, “name.b”: “b12”}):
mycollection.find({“name” : {“$elemMatch”: {“a”: “a11”, “b”:
“b12”}}}):无结果
{u'age': 20, u'_id': 1, u'name': [u'a', u'b', u'c']}
{u'age': 20, u'_id': 1, u'name': [{u'a': u'a11', u'b': u'b11'}, {u'a': u'a12', u'b': u'b12'}]}
结果
结果
42. 查找—子文档、$or
db.collection.find( { “name”: {”first ”: ‘Hello’,
”last ” : ‘World’ } } ) 会做完全匹配;
{ “name”: {”first ”: ‘Hello’, ”last ” :
‘World’, “other”:’Hei’ } } 不会匹配;
要想匹配,需要用 dot 表示法:
db.collection.find( { “name.first ”: ‘Hello’,
”name.last ” : ‘World’ } )
关于 $or 表达式:
会返回满足 “name.first”:”AAA” 和 “age”:30 的。
mycollection.find(
{ "$or": [
{ 'name.first' : "AAA" },
{ "age": 30 }
]
}
)
结果
43. 查找—limit、sort
SQL: select * from table limit 10;
MongoDB: db.collection.find().limit( num)
SQL: select * from table order by column asc;
MongoDB: db.collection.find().sort(“field”:1)
–mycollection.insert({"_id":1, "score":32})
–mycollection.insert({"_id":2, "score":62})
–mycollection.insert({"_id":3, "score":42})
–mycollection.insert({"_id":4, "score":90})
–mycollection.insert({“_id”:5, “score”:10})
–mycollection.find({}).limit(3).sort([("score",
pymongo.DESCENDING)])
{u'_id': 4, u'score': 90}
{u'_id': 2, u'score': 62}
{u'_id': 3, u'score': 42}
结果
45. 内容
• 简介
• 安装
• 启动、停止
• 插入、删除、更新、查找
• 聚合、Map-Reduce、索引
• 高级主题:复制、分片
• 管理
47. 聚合
• 下面采用mongo shell(JS)示例聚合:
> db.colors.insert({name:'red', primary:true})
> db.colors.insert({name:'green', primary:true})
> db.colors.insert({name:'blue', primary:true})
> db.colors.insert({name:'purple', primary:false})
> db.colors.insert({name:'orange', primary:false})
> db.colors.insert({name:'yellow', primary:false})
> db.people.insert({name:'John', age:28})
> db.people.insert({name:'Steve', age:29})
> db.people.insert({name:'Steph', age:27})
50. > db.items.insert({title:'Home', template:'home'})
> db.items.insert({title:'What We Do', template:'page'})
> db.items.insert({title:'Our Writing', template:'page'})
> db.items.insert({title:'Who We Are', template:'page'})
> db.items.insert({title:'Hire Us', template:'page'})
> var key = {template: true};
> var initial = {count:0};
> var reduce = function(obj, prev) { prev.count += 1; };
> db.items.group({key:key, initial:initial, reduce:reduce})
[
{"template" : "home", "count" : 1},
{"template" : "page", "count" : 4}
]
52. Map-Reduce
• 同样通过mongo shell(JS)演示:
> db.items.insert({tags: ['dog', 'cat']})
> db.items.insert({tags: ['dog']})
> db.items.insert({tags: ['dog', 'mouse']})
> db.items.insert({tags: ['dog', 'mouse',
'hippo']})
> db.items.insert({tags: ['dog', 'mouse',
'hippo']})
> db.items.insert({tags: ['dog', 'hippo']})
53. > var map = function() {
this.tags.forEach(function(t) {
emit(t, {count: 1});
});
}
> var reduce = function(key, values) {
var count = 0;
for(var i=0, len=values.length; i<len; i++) {
count += values[i].count;
}
return {count: count};
}
54. > var map = function() {
this.tags.forEach(function(t) {
emit(t, {count: 1});
});
}
> var reduce = function(key, values) {
var count = 0;
for(var i=0, len=values.length; i<len; i++) {
count += values[i].count;
}
return {count: count};
}
55. > var result = db.items.mapReduce(map, reduce, {
out: “map_reduce_example” });
> db.map_reduce_example.find()
{ "_id" : "cat", "value" : { "count" : 1 } }
{ "_id" : "dog", "value" : { "count" : 6 } }
{ "_id" : "hippo", "value" : { "count" : 3 } }
{ "_id" : "mouse", "value" : { "count" : 3 } }
57. • 索引操作
–建立索引(Mongo Shell)
– db.collection.ensureIndex(Index_pattern)
• db.people.ensureIndex({pn:1})#按pn升序索引
• db.collection.ensureIndex( { a: 1, b: 1, c: 1 } )建立
复合索引
• db.collection.ensureIndex( {a: 1},{unique: true })建立
唯一索引
db.collection.ensureIndex({a: 1},{dropDups: true})删除重
复值
db.users.ensureIndex({ twitter_name: 1},{sparse: true} )
建立稀疏索引,对不存在索引字段的项不索引
db.collection.ensureIndex({a:“hashed”})建立hash索引
58. • 索引操作
–删除索引
• 可以从一个集合中删除索引
• 示例:db.accounts.dropIndex( { "tax-id": 1 } )
–使用explain():
• 在任何查询游标后使用 explain 可以查看查询所使用的索引
状况。
–使用hint():
• 可以强制要求查询游标使用某种索引
db.people.find( { name: "John Doe", zipcode: { $gt: 63000 } } } ).hint( { zipcode: 1 } )
db.people.find( { name: “John Doe”, zipcode: { $gt: 63000 } } } ).explain()
59. 内容
• 简介
• 安装
• 启动、停止
• 插入、删除、更新、查找
• 聚合、Map-Reduce、索引
• 高级主题:复制、分片
• 管理
64. • 副本集-搭建
–以搭建三个实例为例:
– mkdir -p /srv/mongodb/rs0-0 /srv/mongodb/rs0-1
/srv/mongodb/rs0-2
– mongod --port 27017 --dbpath /srv/mongodb/rs0-0 --replSet rs0
– mongod --port 27018 --dbpath /srv/mongodb/rs0-1 --replSet rs0
– mongod --port 27019 --dbpath /srv/mongodb/rs0-2 --replSet rs0
– mongo --port 27017 连接到一个mongod实例
– rsconf = { _id: "rs0", members: [ { _id: 0, host:
"<hostname>:27017" } ] }
– 初始化:rs.initiate( rsconf )
– 增加副本:rs.add("<hostname>:27018") rs.add("<hostname>:27019")
– 删除副本:rs.remove("<hostname>:27017")
– 修改副本:cfg = rs.conf()
cfg.members[0].host = "mongo2.example.net:27019"
rs.reconfig(cfg)
•
副本集-分片-配置服务器 搭建
65. • 配置服务器-搭建
–建立数据存放目录:
• mkdir /data/configdb
–启动配置服务器:
• mongod --configsvr --dbpath <path> --port
<port>
–配置分片:需要使用mongos连接配置服务器进行配置
,也可以参考各个语言驱动来配置。
副本集-分片-配置服务器 搭建
66. • 分片-搭建
–需要启动mongos连接配置服务器来进行配置。
–启动:mongos --configdb <config server
hostnames>
–启动mongo,连接mongos:
• mongo --host <hostname of machine running mongos> --
port <port mongos listens on>
–增加分片:
• sh.addShard( “rs1/ip:port” )
• rs1为副本集名称,ip:port 为副本集的任何一个mongod。
副本集-分片-配置服务器 搭建
67. • 使用分片
–添加分片后,如果需要对某个库或集合使用分片,需
要执行如下操作:
• sh.enableSharding("<database>")
• db.runCommand( { enableSharding: <database> } )
• sh.shardCollection("<database>.<collection>", shard-
key-pattern)
• shard-key-pattern 与建立索引的方式一致。
副本集-分片-配置服务器 搭建
sh.shardCollection("records.people", { "zipcode": 1, "name": 1 } )
sh.shardCollection("people.addresses", { "state": 1, "_id": 1 } )
sh.shardCollection("assets.chairs", { "type": 1, "_id": 1 } )
示例
70. 内容
• 简介
• 安装
• 启动、停止
• 插入、删除、更新、查找
• 聚合、Map-Reduce、索引
• 高级主题:复制、分片
• 管理
72. 备份-恢复
使用Mongodump备份
mongodump --dbpath /data/db/ --out /data/backup/
–导出的是bson结构的,通过--collection collection --db test
可以指定集合和数据库。
–使用--oplog:在副本集中使用oplog确保备份的数据是一致的,
系统会同时备份日志文件。
使用mongorestore恢复
–mongorestore --port <port number> <path to the backup>
–可以使用mongorestore --filter ‘{“field”: 1}’过滤一些
数据
–使用--oplogReplay:该选项确保恢复的数据也是一致的。
75. 导入-导出数据
• 与备份-恢复不同,导入-导出只的是导数据库中的部分数
据,不涉及整个db。
• mongoexport: 导出到json文件或控制台输出。
–mongoexport --collection collection --out collection.json
–可以加入 –query指定查询条件
–Mongod若没运行,可以使用: --dbpath 指定数据库路径
mongoimport:
–mongoimport --collection collection --file
collection.json
–Mongod若没运行,可以使用: --dbpath 指定数据库路径
• copydb, clone, cloneCollection:数据库,集合的移动
操作。
77. 查看副本集:
connect mongod: >rs.status()
查看分片:
connect mongos: >use config >db.shards.find({}) #查看分片host
>sh.status() #查看分片状态
查看查询使用的状态:
connect mongod/mongos: >db.collection.find(condition).explain()
查看索引:
connect mongod/mongos: >db.system.indexes.find({})