您的位置:首页 > 数据库 > Mongodb

MongoDB入门

2016-01-01 20:41 323 查看

mongodb各个版本的区别

MongoDB for Windows 64-bit 适合 64 位的 Windows Server 2008 R2,

Windows 7 , 及最新版本的 Window 系统。

MongoDB for Windows 32-bit 适合 32 位的 Window 系统及最新的 Windows Vista。 32 位系统上 MongoDB 的数据库最大为 2GB。

MongoDB for Windows 64-bit Legacy 适合 64 位的 Windows Vista,Windows Server 2003, 及 Windows Server 2008 。

搭建简单的mongodb服务器:

建立文件夹data,log,conf,bin,将编译好的mongod放入bin,在conf中新建mongod.conf文件


port = 12345
dbpath = data
logpath = log/mongod.log
fork = true    # linux下表示启动fork进程,windows下无效


启动mongodb: bin/mongod -f conf/mongod.conf

上述安装方法同时适用windows和linux.mongodb的安装包解压后bin目录包含已编译好的可执行程序.

连接mongodb服务器

使用mongdb客户端:mongo 127.0.0.1:12345/test

关闭服务:db.shutdownServer()

基本命令

show dbs 显示库

admin (empty)

imooc 0.078GB

local 0.018GB

use imooc 使用库

switched to db imooc

db.dropDatabase() 删除数据库

use imooc 再次创建库

db.imooc_collection.insert({x:1}) 向集合(表)中插入文档(行)

WriteResult({“nInserted”: 1})

show collections

immoc_collections

system.indexed

db.imooc_collection.find() 返回所有文档

{“_id”: ObjectId(“123123123123123132”), “x” :1}

_id是mongodb自己生成的全局唯一字段,也可以自己指定

db.imooc_collection.insert({x:3, _id:1})

写入成功

db.imooc_collection.insert({x:3, _id:1})

报错,因为_id重复

db.imooc_collection.find({x:1})

for(i=3;i<100;i++) db.imooc_collection.insert({x:i}) 使用js语法

db.imooc_collection.find().count()

99

db.imooc_collection.find().skip(3).limit(2).sort({x:1})

按照x字段排序,跳过3条,限制2条,相当于分页 返回x:4和x:5

数据更新

使用update语句,至少接受2个参数

- db.imooc_collection.insert({x:100, y:100, z:100})

- db.imooc_collection.update({z:100}, {$set:{y:99}})

set是部分更新操作符,只有y改为99,x和z不变

存在的字段会更新,不存在的字段会保持原样

- 试图更新一条不存在的数据时db.imooc_collection.update({y:100}, {y:999})

返回结果WriteResult({“nMatched”: 0, “nUpserted”: 0, “nModified”: 0}) 没有做任何操作,也不报错

- db.imooc_collection.find({y: 999})

无返回,表明刚才的update并没有新建文档

- db.imooc_collection.update({y:100}, {y:999}, true)

true表示如果数据不存在,就写入新的数据

- db.imooc_collection.find({y:999})

返回一条数据

更新多条数据

默认情况下,update语句只更新一条找到的数据,这样设计是为了防止误操作

- db.imooc_collection.update({c:1}, {$set:{c:2}}, false, true)

会将所有c:1的文档改为c:2,且其他元素不变

删除数据

db.imooc_collection.remove()

将会报错,不允许不传参数,这样设计是为了防止误操作,删除所有数据

db.imooc_collection.remove({c:2})

将删除所有c:2的元素

db.imooc_collection.drop()

将删除集合imooc_collection

show tables

system.indexed

创建索引

在数据量较小是,不使用索引查询数据也很快,但数据量大时,使用索引会加快查询速度

use imooc

db.imooc_collection.getIndexes() 显示集合的索引

db.imooc_collection.ensureIndex({x
4000
:1})

x为1代表正向排序,-1表示倒向排序

如果文档较多,创建索引消耗时间多,如果系统负载较大,且有很多存在的文档,不能直接使用这个命令,否则严重影响数据库的性能

索引的种类

_id索引: 是绝大多数集合默认建立的唯一索引

单键索引: 是最普通的索引,单键索引不会自动创建 db.imooc_2.ensureIndex({x:1})

多建索引: 创建形式与单键相同,区别在于字段的值. 多键索引值具有多个记录,例如数组.

db.imooc_2.insert({x: [1,2,3,4]}) mongodb会为这条数据创建一个多键索引

符合索引: 查询条件不只有一个时,就需要建立复合索引

插入{x:1, y:2, z:3}记录, 按照x与y的值查询,需要建立如下索引

db.collection.ensureIndex({x:1, y:1})

然后就可以查询了 db.imooc_2.find({x:1, y:2})

过期索引

是在一段时间后会过期的索引.在索引过期后,相应的数据会被删除.这适合存储一些在一段时间之后会失效的数据比如用户的登录信息,存储的日志等.

格式: db.collection.ensureIndex({time:1}, {expireAfterSeconds:10})

db.imooc_2.ensureIndex({time:1},{expireAfterSeconds:30})

过期索引的限制:

存储在过期索引字段的值必须是指定的时间类型,必须是ISODate或者ISODate数组,不能使用时间戳,否则不能被自动删除.

如果指定了ISODate数组,则按照最小的时间进行删除

过期索引不能是复合索引

删除时间不是精确的.删除过程是由后台程序每60秒跑一次,而且删除也需要一些时间,所以存在误差.

全文索引(文本索引)

对字符串与字符串数组创建全文可搜索的索引

适用情况:

{author:"", title:"", article:""}
db.articles.ensureIndex({key:"text"})
db.articles.ensureIndex({key_1:"text", key_2:"text"})
db.articles.ensureIndex({"$**":"text"})  表示对集合中所有字段创建大的全文索引
</pre>
注意: 一个数据集合只允许创建一个全文索引
使用全文索引:
db.articles.find({$text: {$search: "coffee"}})
db.articles.find({$text: {$search: "aa bb cc"}})  查找多个关键词,用空格隔开 (或查询)
db.articles.find({$text: {$search: "aa bb -cc"}})  包含aa或bb, 不包含cc
db.articles.find({$text: {$search: "\"aa\" \"bb\" \"cc\""}})  包含aa且包含bb且cc
全文索引相似度查询:
$meta操作符: {score:{$meta: "textScore"}}写在查询条件后面可以返回 返回结果 的相似度.
与sort一起使用,可以达到很好的实用效果
db.articles.find({$text: {$search: "aa bb cc"}}, {score:{$meta:"textScore"}})
返回结果中会多了一个score字段, 字段的值越大,相似度越高
db.articles.find({$text: {$search: "aa bb cc"}}, {score:{$meta:"textScore"}}).sort({score:{$meta:"textScore"}})
全文索引的使用限制:
每次查询,只能指定一个$text查询
$text查询不能出现在$nor查询中
查询中如果包含了$text,hint不再起作用 (hint的作用是指定使用的索引)
很可惜,mongodb全文索引还不支持中文


索引属性:名字 唯一性 稀疏性 是否定时删除

索引名字长度限制:125字节.

db.imooc_2.ensureIndex({x:1,y:1,z:1}, {name:”normal_index”}) 自己给索引命名

db.imooc_2.dropIndex({“normal_index”}) 删除索引可以使用名字

唯一性,unique指定:db.collection.ensureIndex({},{unique:true/false})

例如,db.imooc_2.ensureIndex({m:1,n:1}, {unique:true})

db.imooc_2.insert({m:1,n:2})

db.imooc_2.insert({m:1,n:2}) 报错,提示key冲突

稀疏性, sparse指定: 默认不稀疏

db.collection.ensureIndex({},{sparse:true/false})

如果为一个字段创建了索引,但是插入了一条数据没有该字段,如果指定了sparse为true,则不会为这条记录创建索引.

稀疏性的好处是,节省磁盘空间,提高插入速度

是否定时删除,expireAfterSeconds指定:TTL,过期索引

2D索引详解

2D索引: 平面地理位置索引
创建方式db.collection.ensureIndex({w:"2d"})
例如db.location.ensureIndex({"w":"2d"})
位置表示方式:经纬度[经度,纬度]
取值范围:经度[-180,180] 纬度[-90,90]
db.location.insert(w:[1,1])
db.location.insert(w:[100, 100])  # 纬度超过范围,但不会报错,但查询时会有错误
db.location.find({w:{$near:[1,1], $maxDistance:10}})
near会默认返回100个, maxDistance规定最大距离是10
$geoWithin查询: 查询某个形状内的点.
1. $box: 矩形,使用
{$box:[[<x1>, <y1>],[<x2>, <y2>]]} 第一个坐标表示左边界,第二个坐标表示右边界.
2. $center: 圆形,使用
{$center:[[<x1>,<y1>],r]}表示 x1和y1表示圆心位置, r表示半径
3. $polygon: 多边形,使用{$polygon:[[<x1>,<y1>],[<x2>,<y2>],[<x3>,<y3>]]}
使用geoWithin查询
db.location.find({w:{$geoWithin:{$box:[[0,0],[3,3]]}}}) box查询矩形中的点
db.location.find({w:{$geoWithin:{#center:[[0,0],5]}}})
db.location.find({w:{$geoWithin:{$polygon:[[0,0],[0,1],[2,5],[6,1]]}}})

使用geoNear查询:near查询操作符的进化版,geoNear使用runCommand命令进行使用,常用使用如下:
db.runCommand({
geoNear:<collection>,
near:[x,y],
minDistance:(对2D索引无效),
maxDistance:
num:
...})

2Dsphere索引: 球面地理位置索引


MongoDB安全概览

最安全的是物理隔离: 不现实

网络隔离其次

防火墙其次

用户名密码在最后

MongoDB默认不启用权限认证,启用方法

auth开启,修改conf文件

port=12345
dbpath=data
logpath=log/mongod.log
bind_ip=127.0.0.1
verbose=vvvvv
fork=true
auth=true


并且重启mongod服务

MongoDB创建用户:

创建语法:createUser(2.6之前为addUser)

{

user: “”,

pwd: ‘””,

customData:{},

roles:[{role: “”, db:””}]

}

角色类型: 内建类型(read,readWrite,dbAdmin,dbOwner,userAdmin)

keyfile开启
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mongodb 数据库