Windows安装
下载
在官网下载msi安装文件,安装到某个文件夹
配置
在安装后的根目录下创建三个文件夹
- data 存放数据
- log 存放日志
- conf 存放配置文件
在log下创建mongodb.log文件,用来写入日志
在conf下创建mongodb.conf文件,写入以下配置
dbpath=E:\Development\mongoDB\Server\3.2\data #数据库路径
logpath=E:\Development\mongoDB\Server\3.2\log\mongodb.log #日志输出文件路径
logappend=true #错误日志采用追加模式,配置这个选项后mongodb的日志会追加到现有的日志文件,而不是从新创建一个新文件
journal=true #启用日志文件,默认启用
quiet=true #这个选项可以过滤掉一些无用的日志信息,若需要调试使用请设置为false
port=27017 #端口号 默认为27017
指定数据存放目录
用管理员打开命令窗口,进入bin目录下,输入以下命令
mongod --dbpath E:\Development\mongoDB\Server\3.2\data
浏览器访问http://localhost:27017,出现下面提示则成功启动
It looks like you are trying to access MongoDB over HTTP on the native driver port.
将mongoDB安装为Windows服务
用管理员打开命令窗口,输入以下命令,安装mongoDB为Windows服务
sc create MongoDB binPath= "E:\Development\mongoDB\Server\3.2\bin\mongod.exe --service --config=E:\Development\mongoDB\Server\3.2\conf\mongodb.conf"
然后环境变量,将安装的bin目录路径添加到path下,如:
E:\Development\mongoDB\Server\3.2\bin
MongoDB基本使用
MongoDB Shell
打开Windows命令行,输入mongo即可进入mongoDB Shell
基本使用:
输入show datatbases或show dbs可查看当前数据库占用空间
输入use test,切换到test数据库,当test不存在时,会创建test数据库;输入db.dropDatabase()删除test数据库
insert(增)
输入以下命令,会在restaurants集合下添加数据,如果restaurants不存在则会创建,mongoDB数据是以json格式存储的
db.restaurants.insert(
{
"address" : {
"street" : "2 Avenue",
"zipcode" : "10075",
"building" : "1480",
"coord" : [ -73.9557413, 40.7720266 ]
},
"borough" : "Manhattan",
"cuisine" : "Italian",
"grades" : [
{
"date" : ISODate("2014-10-01T00:00:00Z"),
"grade" : "A",
"score" : 11
},
{
"date" : ISODate("2014-01-16T00:00:00Z"),
"grade" : "B",
"score" : 17
}
],
"name" : "Vella",
"restaurant_id" : "41704620"
}
)
可用javascript代码进行多条插入
for(i = 0; i<100; i++)db.restaurants.insert({"age": i})
如果没有给数据指定’_id’字段,mongoDB会自动加入
可用show collections或show tables查看当前的数据库下的数据集合
mongoDB中数据库(database)下是集合(collection) .集合中存储json格式的文档(document)
find(查)
输入以下命令则可以查找集合下的所有数据
db.restaurants.find()
检索查询
输入json格式的字段即可检索查询
//基本
db.restaurants.find( { "borough": "Manhattan" } )
//层级数据
db.restaurants.find( { "address.zipcode": "10075" } )
//小于($lt表示<)
db.restaurants.find( { "grades.score": { $lt: 10 } } )
//逻辑'and'
db.restaurants.find( { "cuisine": "Italian", "address.zipcode": "10075" } )
//逻辑'or'
db.restaurants.find(
{ $or: [ { "cuisine": "Italian" }, { "address.zipcode": "10075" } ] }
)
//计数
db.restaurants.find().count()
//skip(3)跳过前3条数据,limit(2)取两条数据,根据"address.zipcode"升排序
db.restaurants.find().skip(3).limit(2).sort({"address.zipcode": 1})
update(改)
更新操作不能更新id
//更新name为Juni的数据,$set表示只更新cuisine,其他不变
//默认只更新查找到的第一条数据
db.restaurants.update(
{ "name" : "Juni" },
{
$set: { "cuisine": "American (New)" },
$currentDate: { "lastModified": true }
}
)
//更新多条数据
db.restaurants.update(
{ "address.zipcode": "10016", cuisine: "Other" },
{
$set: { cuisine: "Category To Be Determined" },
$currentDate: { "lastModified": true }
},
{ multi: true}
)
//替换,不加入$set即可,即除了_id不变,其他只存储新更新操作中的数据
db.restaurants.update(
{ "restaurant_id" : "41704620" },
{
"name" : "Vella 2",
"address" : {
"coord" : [ -73.9557413, 40.7720266 ],
"building" : "1480",
"street" : "2 Avenue",
"zipcode" : "10075"
}
}
)
//更新一条不存在的数据,在最后加个true表示当没有查找到数据时将新建一条数据
db.restaurants.update(
{"name": "babe"},
{"cup": "36D"},
true
)
remove(删除)
//默认删除所有查找到的数据
db.restaurants.remove( { "borough": "Manhattan" } )
//只删除1条数据
db.restaurants.remove( { "borough": "Queens" }, { justOne: true } )
//删除集合中所有数据
db.restaurants.remove( { } )
//将集合删除
db.restaurants.drop()
索引
_id索引
大部分集合默认建立的索引
单键索引
最普通的索引,不会自动创建
//创建索引
db.collection_1.ensureIndex({"x":1})
//或者以下方式
db.collection_1.createIndex( { "x": 1 } )
多键索引
多键索引和单键索引的区别在于:
-
多键索引的值为多个值,如:数据,对象
-
单键索引的值为单一的值,如:字符串
复合索引
如下,即多个字段
db.restaurants.ensureIndex( { "cuisine": 1, "address.zipcode": -1 } )
过期索引
//创建过期索引,表示插入time的值后,将在30秒后删除
db.time.ensureIndex( {time:1}, {expireAfterSeconds:30} )
//此条记录在插入后30s后删除
db.time.insert( {time:new Date()} )
限制
- 存储在过期索引的字段值必须是指定的时间类型,必须是ISODate或ISODate数组
- 如果指定了ISODate数组,则按最小的值为准
- 过期索引不能是符合索引
- 删除的时间不是精确的,存在误差
全文索引
创建方法
//全文索引值固定为"text"
db.articles.ensureIndex({title:"text"})
//复合索引
db.articles.ensureIndex({title:"text", content:"text"})
//所有索引
db.articles.ensureIndex({"$**":"text"})
使用全文索引查询
//查询包含aa的数据
db.articles.find({$text:{$search:"aa"}})
//查询包含aa或bb或cc的数据,空格表示 或
db.articles.find({$text:{$search:"aa bb cc"}})
//查询包含aa与bb与cc的数据,将数据用\"包含起来表示 与
db.articles.find({$text:{$search:"\"aa\" \"bb\" \"cc\""}})
全文索引相似度
在全文索引查询后添加{score:{$meta:”textScore”}可以返回查询结果的相似度,数值越大相似度越高
db.articles.find({$text:{$search:"aa"}}, {score:{$meta:"textScore"}})
可以跟sort()方法结合
db.articles.find({$text:{$search:"aa"}}, {score:{$meta:"textScore"}})
.sort({score:{$meta:"textScore"})
全文索引限制
-
每次查询只能指定一个$text查询
-
$text查询不能出现在$nor查询中
-
查询中使用了$text,则hint不起作用
索引属性
名字,name指定
可以为索引指定名字
db.collection_1.ensureIndex({"x":1},{name:"customIndex"})
删除索引的时候会方便很多
db.collecion_1.dropIndex("customIndedx")
唯一性,unique指定
索引唯一性,表示不能插入相同的值
db.collection_1.ensureIndex({"d":1,"g":1},{unique:true})
稀疏性,spasre指定
表示不存在m的数据将不创建索引
db.collection_1.ensureIndex({"m":1},{sparse:true})
地理位置索引
2D索引:平面地理位置索引
创建方式
db.location.ensureIndex({w:"2d"})
位置表示方式:经纬度[经度,纬度]
取值范围:经度[-180,180] 纬度[-90,90]
//插入
db.location.insert({w:[120,30]})
//查询,$near会返回100个最近的数据
db.location.find({w:{$near:[100,10]}})
//限制距离最大$maxdistance
db.location.find({w:{$near:[100,10],$maxDistance:10}})
形状的表示{$geoWithin:{$box:[[x1,y1],[x2,y2]]}}
//$box:矩形
{$box:[[x1,y1],[x2,y2]]}
//$center:圆形
{$center:[[x1,y2],r]}
//$phylygon:多边形
{$phylygon:[[x1,y1],[x2,y2],[x3,y3]]}
//实际查询
db.location.find({w:{$geowithin:{$box:[[1,1],[2,2]]}}})
geoNear查询
geoNear使用runCommand进行查询
db.runCommand(
{
geoNear:<collecion>,
near:<x,y>,
minDistance:(2d索引无效),
maxDistance: ,
num:
}
2Dsphere索引:球面地理位置索引
创建方式
db.location.ensureIndex({w:"2dsphere"})
位置表示方式:GeoJSON(描述一个点、一条直线,多边形等形状)
格式:
{type:"", coordinates:[<coordinates>]}
查询方式与2d索引查询类似:还支持$minDistance查询
索引构建情况分析
优点:加快索引相关的查询
缺点:增加磁盘空间消耗,降低写入性能
mongostat
使用mongostat查看mongoDB运行状态
mongostat -h 127.0.0.1:27017
explain()
在查找时可使用explain()查看查询情况
db.collection.find({x:"1"}).explain()
MongoDB安全
MongoDB安全概念
- 物理隔离:不现实
- 网络隔离
- 防火墙隔离
- 用户名密码隔离
开启权限
在conf/mongodb.conf配置文件中添加auth,重启mongoDB
auth = true #开启权限认证
创建用户
创建语法:createUser
db.createUser({user:"<name>",
pwd:"<password>",
customData:"<info>",
roles:[{role:"<role>",db:"<db>"}]
})
角色类型:(内建类型:read,readWrite,dbAdmin,dbOwner,userAdmin)
登录:在进入mongoDB时添加用户名和密码
mongo -u root -p root