> show dbs local 0.000GB # 即使数据库不存在,使用use也会创建 > use changwenDB switched to db changwenDB # 插入数据 > db.changwenDB_collection.insert({x:1}) WriteResult({ "nInserted" : 1 }) > show dbs changwenDB 0.000GB local 0.000GB # show collections是命令,而不是函数。函数有返回值,命令没有 > show collections changwenDB_collection # 查询 > db.changwenDB_collection.find() { "_id" : ObjectId("57bda3bca907419000a16bee"), "x" : 1 } # _id是mongodb是系统自动生成的,全局不能重复,可以自己指定 > db.changwenDB_collection.insert({x:2,_id:1}) WriteResult({ "nInserted" : 1 }) > db.changwenDB_collection.insert({x:3,_id:1}) WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 duplicate key error collection: changwenDB.changwenDB_collection index: _id_ dup key: { : 1.0 }" } }) > db.changwenDB_collection.find() { "_id" : ObjectId("57bda3bca907419000a16bee"), "x" : 1 } { "_id" : 1, "x" : 2 } # 带参数的查询 > db.changwenDB_collection.find({x:1}) { "_id" : ObjectId("57bda3bca907419000a16bee"), "x" : 1 } # 多条插入 > for(i=0;i<10; i++)db.changwenDB_collection.insert({x:1}) WriteResult({ "nInserted" : 1 }) > db.changwenDB_collection.find() { "_id" : ObjectId("57bda3bca907419000a16bee"), "x" : 1 } { "_id" : 1, "x" : 2 } { "_id" : ObjectId("57bda4a5a907419000a16bef"), "x" : 1 } { "_id" : ObjectId("57bda4a5a907419000a16bf0"), "x" : 1 } { "_id" : ObjectId("57bda4a5a907419000a16bf1"), "x" : 1 } { "_id" : ObjectId("57bda4a5a907419000a16bf2"), "x" : 1 } { "_id" : ObjectId("57bda4a5a907419000a16bf3"), "x" : 1 } { "_id" : ObjectId("57bda4a5a907419000a16bf4"), "x" : 1 } { "_id" : ObjectId("57bda4a5a907419000a16bf5"), "x" : 1 } { "_id" : ObjectId("57bda4a5a907419000a16bf6"), "x" : 1 } { "_id" : ObjectId("57bda4a5a907419000a16bf7"), "x" : 1 } { "_id" : ObjectId("57bda4a5a907419000a16bf8"), "x" : 1 } > db.changwenDB_collection.find().count() 12 > db.changwenDB_collection.find().skip(3).limit(2).sort({x:1}) { "_id" : ObjectId("57bda4a5a907419000a16bf1"), "x" : 1 } { "_id" : ObjectId("57bda4a5a907419000a16bf2"), "x" : 1 } >
# 将x=1更新为x=99 > db.changwenDB_collection.update({x:1},{x:99}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.changwenDB_collection.find() { "_id" : ObjectId("57bda3bca907419000a16bee"), "x" : 99 } { "_id" : 1, "x" : 2 } > db.changwenDB_collection.insert({x:100,y:100,z:100}) WriteResult({ "nInserted" : 1 }) > db.changwenDB_collection.find() { "_id" : ObjectId("57bee69ea907419000a16bfb"), "x" : 100, "y" : 100, "z" : 100 } # 如果这么更新,会将,y,z覆盖,只剩下x > db.changwenDB_collection.update({z:100},{x:99}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.changwenDB_collection.find() { "_id" : ObjectId("57bee69ea907419000a16bfb"), "x" : 99 } # set部分更新 > db.changwenDB_collection.update({z:100},{$set:{x:99}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.changwenDB_collection.find() { "_id" : ObjectId("57bee82d97bc76e52551f81e"), "x" : 99, "y" : 100, "z" : 100 }更新不存在的数据
# x=100不存在,就将x=111,(需要加true);存在则更新 > db.changwenDB_collection.update({x:100},{x:111},true) WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : ObjectId("57bee8f1eecfb943edb7f1e5") })更新多条数据:默认只能更新一条
> for(i=0;i<3; i++)db.changwenDB_collection.insert({x:1}) WriteResult({ "nInserted" : 1 }) > db.changwenDB_collection.find() { "_id" : ObjectId("57bee82d97bc76e52551f81e"), "x" : 99, "y" : 100, "z" : 100 } { "_id" : ObjectId("57bee8f1eecfb943edb7f1e5"), "x" : 111 } { "_id" : ObjectId("57beea1e97bc76e52551f81f"), "x" : 1 } { "_id" : ObjectId("57beea1e97bc76e52551f820"), "x" : 1 } { "_id" : ObjectId("57beea1e97bc76e52551f821"), "x" : 1 } > db.changwenDB_collection.update({x:1},{$set:{x:2}},false,true) WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 }) > db.changwenDB_collection.find() { "_id" : ObjectId("57bee82d97bc76e52551f81e"), "x" : 99, "y" : 100, "z" : 100 } { "_id" : ObjectId("57bee8f1eecfb943edb7f1e5"), "x" : 111 } { "_id" : ObjectId("57beea1e97bc76e52551f81f"), "x" : 2 } { "_id" : ObjectId("57beea1e97bc76e52551f820"), "x" : 2 } { "_id" : ObjectId("57beea1e97bc76e52551f821"), "x" : 2 }
默认删除所有查找到的数据
> db.changwenDB_collection.remove({x:2}) WriteResult({ "nRemoved" : 3 }) > db.changwenDB_collection.find() { "_id" : ObjectId("57bee82d97bc76e52551f81e"), "x" : 99, "y" : 100, "z" : 100 } { "_id" : ObjectId("57bee8f1eecfb943edb7f1e5"), "x" : 111 } # 删除表 > db.changwenDB_collection.drop() true > show tables
数据量较大时,需要创建索引
> db.changwenDB_collection.insert({x:1}) WriteResult({ "nInserted" : 1 }) > db.changwenDB_collection.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.changwenDB_collection" } ] -- 创建索引,key值代表方法,1为正向,-1为负向。最好创建数据库前就创建索引 > db.changwenDB_collection.ensureIndex({x:1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.changwenDB_collection.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.changwenDB_collection" }, { "v" : 1, "key" : { "x" : 1 }, "name" : "x_1", "ns" : "test.changwenDB_collection" } ]
-- 对于这条插入语名,MongoDB便创建了多键索引 > db.changwen2.insert({x:[1,2,3,4,5]}) WriteResult({ "nInserted" : 1 })
> db.changwen2.ensureIndex({x:1,y:1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.changwen2.find({x:1,y:2})
> db.changwen2.ensureIndex({time:1},{expireAfterSeconds:30}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 2, "numIndexesAfter" : 3, "ok" : 1 } > db.changwen2.insert({time:new Date()}) WriteResult({ "nInserted" : 1 }) > db.changwen2.find() { "_id" : ObjectId("57bef11697bc76e52551f823"), "x" : 1 } { "_id" : ObjectId("57bef87697bc76e52551f826"), "time" : ISODate("2016-08-25T13:53:58.190Z") } > db.changwen2.find() { "_id" : ObjectId("57bef11697bc76e52551f823"), "x" : 1 } -- 删除不了,对应限制2 > db.changwen2.insert({time:11}) WriteResult({ "nInserted" : 1 }) > db.changwen2.find() { "_id" : ObjectId("57bef11697bc76e52551f823"), "x" : 1 } { "_id" : ObjectId("57bef90197bc76e52551f827"), "time" : 11 }过期索引的限制:
> db.changwen2.ensureIndex({"article":"text"}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 3, "numIndexesAfter" : 4, "ok" : 1 } > db.changwen2.insert({"article":"aa bb cc dd ee"}) WriteResult({ "nInserted" : 1 }) > db.changwen2.insert({"article":"aa bb cc gg"}) WriteResult({ "nInserted" : 1 }) > db.changwen2.insert({"article":"aa bb cc rr"}) WriteResult({ "nInserted" : 1 })
-- 查询含有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"}})
-- 查询含有aa且含有bb且含有cc的数据
db.articles.find({$text:{$search:"\"aa\" \"bb\" \"cc\""}})
> db.changwen2.find({$text:{$search:"aa dd"}}) { "_id" : ObjectId("57bf042b97bc76e52551f828"), "article" : "aa bb cc dd ee" } { "_id" : ObjectId("57bf043197bc76e52551f829"), "article" : "aa bb cc gg" } { "_id" : ObjectId("57bf043597bc76e52551f82a"), "article" : "aa bb cc rr" } > db.changwen2.find({$text:{$search:"aa bb -dd"}}) { "_id" : ObjectId("57bf043197bc76e52551f829"), "article" : "aa bb cc gg" } { "_id" : ObjectId("57bf043597bc76e52551f82a"), "article" : "aa bb cc rr" } > db.changwen2.find({$text:{$search:"\"aa\" \"dd\""}}) { "_id" : ObjectId("57bf042b97bc76e52551f828"), "article" : "aa bb cc dd ee" }
> db.changwen2.insert({"article":"aa bb"}) WriteResult({ "nInserted" : 1 }) > db.changwen2.find({$text:{$search:"aa bb"}},{score:{$meta:"textScore"}}).sort({score:{$meta:"textScore"}}) { "_id" : ObjectId("57bf10a297bc76e52551f82b"), "article" : "aa bb", "score" : 1.5 } { "_id" : ObjectId("57bf043197bc76e52551f829"), "article" : "aa bb cc gg", "score" : 1.25 } { "_id" : ObjectId("57bf043597bc76e52551f82a"), "article" : "aa bb cc rr", "score" : 1.25 } { "_id" : ObjectId("57bf042b97bc76e52551f828"), "article" : "aa bb cc dd ee", "score" : 1.2 }全文索引的使用限制
> db.changwen2.ensureIndex({x:1}) -- 可以看到索引的名字由key_value组成"x_1",其中1和-1表示索引 的方向 > db.changwen2.getIndexes() [ ... { "v" : 1, "key" : { "x" : 1 }, "name" : "x_1", "ns" : "changwen2.changwen2" } ] > db.changwen2.ensureIndex({y:-1}) db.changwen2.ensureIndex({x:1,y:-1}) --那么结果会是"x_1_y_-1" -- 如果名字很长,不好记,而且有长度限制。自定义为如下 db.changwen2.ensureIndex({x:1,y:1,z:1,m:1,{name:"normal_index"}) db.changwen2.dropIndex("normal_index")2).唯一性
db.changwen2.ensureIndex({m:1,n:1},{unique:true}) db.changwen2.insert({m:2,n:3}}) -- 再次插入会有异常 db.changwen2.insert({m:2,n:3}})3).稀疏性
db.changwen2.insert({m:5}) db.changwen2.insert({n:5}) -- 查找只存在m,不存在n的数据 db.changwen2.find({m:{$exists:true}}) -- 创建稀疏索引 db.changwen2.ensureIndex({m:1},{sparse:true}) -- 存在m不存在的数据 db.changwen2.find({m:{$exists:false}}) db.changwen2.getIndex() -- hint强制使用索引 db.changwen2.find({m:{$exists:false}}).hint("m_1")4).是否定时删除
概念:将一些点的位置存储在MongoDB中,创建索引后,可以按照位置来查找其他点。
子分类:
2d索引,用于存储和查找平面上的点
2dsphere索引,用于存储和查找球面上的点
查找方式:
1.查找距离某个点一定距离内的点
2.查找包含在某区域内的点
2D索引:平面地理位置索引
创建方式:db.collection.ensureIndex({w:"2d"})
位置表示方式:经纬度[经度,纬度]
取值范围:经度[-180,180] 纬度[-90,90]
查询方式:
1).$near查询:查询某个距离某个点最近的点
2).$geoWithin查询:查询某个形状地点
形状的表示:
1).$box:矩形,使用{$box:[[
2).$center:圆形,使用{$center:[[
3).$polygon:多边形,使用{$polygon:[[
db.location.ensureIndex({w:"2d"}) db.location.insert({w:[1,1]}) db.location.insert({w:[1,2]}) db.location.insert({w:[3,2]}) db.location.insert({w:[50,50]}) db.location.insert({w:[180,50]}) -- near查询距离"1,1"最近的点,maxDistance限制最远点的距离是10 db.location.find({w:{$near:[1,1],$maxDistance:10}}) -- 在2d索引中不支持min查询goeWithin查询
> db.location.find({w:{$geoWithin:{$box:[[0,0],[2,3]]}}}) { "_id" : ObjectId("57c10675b5ef0e591d607d81"), "w" : [ 1, 1 ] } { "_id" : ObjectId("57c10681b5ef0e591d607d82"), "w" : [ 1, 2 ] } > db.location.find({w:{$geoWithin:{$center:[[0,0],3]}}}) { "_id" : ObjectId("57c10675b5ef0e591d607d81"), "w" : [ 1, 1 ] } { "_id" : ObjectId("57c10681b5ef0e591d607d82"), "w" : [ 1, 2 ] } > db.location.find({w:{$geoWithin:{$polygon:[[0,0],[0,1],[2,5],[6,1]]}}}) { "_id" : ObjectId("57c10675b5ef0e591d607d81"), "w" : [ 1, 1 ] } { "_id" : ObjectId("57c10681b5ef0e591d607d82"), "w" : [ 1, 2 ] } { "_id" : ObjectId("57c10686b5ef0e591d607d83"), "w" : [ 3, 2 ] }比near更高级的查询--geoNear
> db.runCommand({geoNear:"location",near:[1,2],maxDistance:10,num:1}) { "waitedMS" : NumberLong(0), "results" : [ { "dis" : 0, "obj" : { "_id" : ObjectId("57c10681b5ef0e591d607d82"), "w" : [ 1, 2 ] } } ], "stats" : { "nscanned" : 3, "objectsLoaded" : 1, "avgDistance" : 0, "maxDistance" : 0, "time" : 0 }, "ok" : 1 }
概念:球面地理位置索引
创建方式:db.collection.ensureIndex({w:"2dsphere"})
位置表示方式:
GeoJSON:描述一个点,一条直线,多边形等形状
格式:{type:"",coordinates:[
查询方式与2d索引查询方式类似,支持$minDistance与$maxDistance
索引构建情况分析
索引好处:加快索引相关的查询
索引不好处:增加磁盘空间消耗,降低写入性能
如何评判当前索引构建情况
1).mongostat工具介绍
mongostat:查看mongodb运行状态的程序
使用说明:mongostat -h 127.0.0.1:12345
索引情况:idx miss
> for(i=0;i<10000;i++)db.changwen2.insert({x:i}) WriteResult({ "nInserted" : 1 }) --执行上面的语句后,立马执行下面的语句 changwen@ubuntu:~/user_project/mongodb_simple1/bin$ mongostat -h 127.0.0.1:12345 connected to: 127.0.0.1:12345 warning: detected a 3.0 mongod, some columns not applicable insert query update delete getmore command mapped vsize res faults locked db idx miss % qr|qw ar|aw netIn netOut conn time 2415 *0 *0 *0 0 1|0 0m 263m 78m 0 Metadata:0.0% 0 0|0 0|0 306k 118k 2 21:11:48 2768 *0 *0 *0 0 1|0 0m 264m 79m 0 Metadata:0.0% 0 0|0 0|0 351k 132k 2 21:11:49 150 *0 *0 *0 0 2|0 0m 264m 79m 0 Metadata:0.0% 0 0|0 0|0 19k 25k 2 21:11:50 *0 *0 *0 *0 0 1|0 0m 264m 79m 0 Metadata:0.0% 0 0|0 0|0 62b 19k 2 21:11:51 *0 *0 *0 *0 0 1|0 0m 264m 79m 0 Metadata:0.0% 0 0|0 0|0 62b 19k 2 21:11:522).profile集合介绍
> db.getProfilingStatus() { "was" : 0, "slowms" : 100 } --为0表示profile是关闭的,不会记录任何数据 --1,2 > db.setProfilingLevel(2) { "was" : 0, "slowms" : 100, "ok" : 1 } > db.getProfilingStatus() { "was" : 2, "slowms" : 100 } > show tables changwen2 location system.profile --这个是刚自动创建的 -- natural自然排序,是按输入先后时间 > db.system.profile.find().sort({$natural:-1}).limit(1) { "op" : "query", "ns" : "changwen2.system.profile", "query" : { "find" : "system.profile", "filter" : { } }, "keysExamined" : 0, "docsExamined" : 0, "cursorExhausted" : true, "keyUpdates" : 0, "writeConflicts" : 0, "numYield" : 1, "locks" : { "Global" : { "acquireCount" : { "r" : NumberLong(4) } }, "Database" : { "acquireCount" : { "r" : NumberLong(2) } }, "Collection" : { "acquireCount" : { "r" : NumberLong(2) } } }, "nreturned" : 0, "responseLength" : 115, "protocol" : "op_command", "millis" : 133, "execStats" : { "stage" : "COLLSCAN", "filter" : { "$and" : [ ] }, "nReturned" : 0, "executionTimeMillisEstimate" : 0, "works" : 2, "advanced" : 0, "needTime" : 1, "needYield" : 0, "saveState" : 1, "restoreState" : 1, "isEOF" : 1, "invalidates" : 0, "direction" : "forward", "docsExamined" : 0 }, "ts" : ISODate("2016-08-27T04:18:51.490Z"), "client" : "127.0.0.1", "allUsers" : [ ], "user" : "" }3).日志介绍
五、mongoDB安全
1).最安全的是物理隔离:不现实
2).网络隔离其次,如使用内网
3).防火墙再其次
4).用户名密码在最后
5-1.开启权限认证
1).auth开启
在mongod.conf中配置auth=true,然后重启下
2).keyfile开启
5-2.在MongoDB中创建用户
1).创建语法:createUser(2.6之前为addUser)
2).{user:"
roles:[{role:"
3).角色类型:内建类型(read,readWrite,dbAdmin,dbOwner,userAdmin)
> db.createUser({user:"changwensir",pwd:"changwensir",roles:[{role:"userAdmin",db:"admin"},{role:"read",db:"test"}]}) Successfully added user: { "user" : "changwensir", "roles" : [ { "role" : "userAdmin", "db" : "admin" }, { "role" : "read", "db" : "test" } ] }5-3.MongoDB用户角色详解