MongoDB

MongoDB是一个基于分布式文件存储的面向文档的数据库,多用于数据采集和分散处理(Map/Reduce),特别是在大数据处理方面比较擅长。

MongoDB 是介于关系/非关系数据库之间的产品,是非关系数据库中最像关系数据库的。查询功能强大,类似关系数据库。

数据/集合操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
show dbs
// 进到test数据库
use test
// 删除当前数据库
db.dropDatabase()

show collections
show tables

// 创建集合
db.createCollection("posts")
// 重命名
db.posts.renameCollection("temp")
// 删除集合
db.temp.drop()

文档操作

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
db.posts.insert({title: 'blog1', author: 'tt'})

db.posts.remove({})

// 查
db.posts.findOne()
db.posts.find({}, {field1: true, field2: 1})
// 参数1:指定过滤条件,参数2:指定显示的属性
// $gte, $gt, $lte, $lt, $eq, $ne, 支持正则
db.posts.find({$or:[{...},{...}]})
db.posts.find({"": {$in: [...]}})
// 存在某个属性的
db.posts.find({"": {$exists: true}})

// 排序 1升序,-1降序
sort({field: 1})
// 共多少个
db.posts.count()
// 跳过多少个(offset)
skip()
// 显示多少个
limit()

// 更新
update(<filter>, <update>, <options>)
// <update> $inc:递加, $mul:相乘, $rename:改名, $set:新增or修改、$unset:字段删除
// <options> {multi: true} 更新多条(默认只更新一条), {upsert: true} 有则更新,无则新增
db.posts.update({"author":"tt"}, {$set: {"author": "tc"}}, {multi: true})
// 更新数组中的元素的字段,使用$占位。col:{arr: [{field: 'old'}]}
db.col.update({'arr.field': 'old'}, {$set: {'arr.$.field': 'new'}})

聚合

https://www.runoob.com/mongodb/mongodb-aggregate.html

管道操作符:

  • $project:修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。
  • $match:用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。
  • $limit:用来限制MongoDB聚合管道返回的文档数。
  • $skip:在聚合管道中跳过指定数量的文档,并返回余下的文档。
  • $unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
  • $group:将集合中的文档分组,可用于统计结果。
  • $sort:将输入文档排序后输出。
  • $geoNear:输出接近某一地理位置的有序文档。

栗子:统计id出现的次数

1
2
3
4
db.user.aggregate([
{ $group : {_id : "$id", count : {$sum : 1}} },
{ $sort: {count: -1} }
])

索引

1
2
3
4
5
6
7
8
getIndexes()
createIndex({...}, {...})
dropIndex({...})

// 逆序
db.posts.createIndex({rank:-1})
// 唯一
db.posts.createIndex({title:1}, {unique:true})

备份还原

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 备份 在./dump/ 目录下
mongodump -d [dbname]
# 还原 --drop 先删除当前数据,然后恢复备份的数据
mongorestore --drop

# 指定主机、库
mongodump -h 127.0.0.1:27017 -d 库名 -o 路径
mongorestore -h 127.0.0.1:27017 -d 库名 路径 --drop

mongoimport --db 'xz_sys' --collection 'website_channls' --file channls.json
mongoexport --db 'xz_sys' --collection 'website_channls' --out channls.json

db.getCollection('tables')
.find({_id: 'q3hrnnoKu2mnCL7kE'})
.forEach(function(x){printjsononeline(x)});

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×