1、Mongodb數據庫之增刪改查mongodb
show databases
show dbs //顯示數據庫;數據庫
show tables
show collections //查示表或者集合;數組
use imooc //使用或建立數據庫imooc;安全
增:
use imooc
db.imooc_collection.insert({x:1}) //往集合名「imooc_collection」插入單條數據「x:1」;ide
db.imooc_collection.insert({x:2}) //往集合名「imooc_collection」插入單條數據「x:2」;
db.imooc_collection.insert({x:100,y:100,z:100}) //往集合名「imooc_collection」插入多字段單條數據;
for(i=3;i<100;i++)db.imooc_collection.insert({x:i}) //往集合名「imooc_collection」批量插入數據「x:3-99」;spa
刪:
db.imooc_collection.remove({c:2}) //刪除集合或表匹配的數據(必須傳遞參數,不然報錯);
db.imooc_collection.drop() //刪除集合或表;排序
use imooc
db.dropDatabase() //刪除數據庫imooc;索引
改:
db.imooc_collection.update({x:1},{x:999}) //更改集合名「imooc_collection」裏「x:1」爲「x:999」;
db.imooc_collection.update({z:100},{$set:{y:99}}) //當查找「z:100」時,只更新y字段爲「y:99」;
db.imooc_collection.update({y:100},{y:999},true) //當查找的數據不存在時,插入一條數據;
db.imooc_collection.update({c:1},{$set:{c:2}},false,true) //批量更新全部匹配的數據;ip
注:mongodb默認只更新查找到的第一條數據,目的是防止update誤操做;rem
查:
db.imooc_collection.find() //查詢集合名「imooc_collection」裏的全部數據內容;
db.imooc_collection.find().count() //統計集合名「imooc_collection」裏的全部數據內容的條數;
db.imooc_collection.find().skip(3) //查詢過濾前3條數據;
db.imooc_collection.find().limit(10) //查詢限制只顯示前10條數據;
db.imooc_collection.find().sort({x:1}) //查詢使用「x」進行排序;
2、索引
增:
db.collection.ensureIndex()
刪:
db.collection.dropIndex("index name")
改:
查:
db.collection.getIndexes()
1._id索引:
use imooc
db.table2.insert({x:1})
db.table2.getIndexes() //_id索引是插入數據時,默認自動建立的惟一索引(該命令爲查詢集合內的索引);
2.單鍵索引:
db.table2.ensureIndex({x:1}) //建立「x:1」的單鍵索引,查詢條件爲一個值時即爲單鍵索引;
3.多鍵索引:
db.table2.insert({x:[1,2,3,4,5]}) //插入一個數組,再建立的索引即爲多鍵索引;
4.複合索引:
db.table2.ensureIndex({x:1,y:2}) //查詢條件不僅一個時建立的索引即爲複合索引;
5.過時索引:
db.table2.insert({time:new Date()}) //插入time:當期時間的一條數據;
db.table2.ensureIndex({time:1},{expireAfterSeconds:30}) //建立鍵值爲time,過時時間爲30後的過時索引;
注:數據必須是ISOdate或者ISODate數組,才能自動刪除;每60秒執行檢測一次;
6.全文索引:
db.table2.ensureIndex({key:"text"})
db.table2.ensureIndex({key_1:"text",ke_2:"text"})
db.table2.ensureIndex({"$**":"text"}) //建立全文索引的三種方法;
db.table2.find({$text:{$search:"aa"}})
db.table2.find({$text:{$search:"aa bb cc"}})
db.table2.find({$text:{$search:"aa bb -cc"}})
db.table2.find({$text:{$search:"\"aa\" \"bb\""}})
db.table2.find({text:{$search:"aa bb"}},{score:{$meta:"textScore"}}).sort({score:{$meta:"textScore"}}) //使用全
文索引的五種方法;
注:全文索引只能指定一個「text」;MongoDB暫不支持中文;
索引重要屬性:
1.名字(name);
2.惟一性(unique);
3.稀疏性(sparse);
4.是否認時刪除(expireAfterSeconds);
7.地理位置索引:
7.1 2d索引
7.2 2dsphere索引
3、mongoDB安全:
1.開啓權限認證;2.建立用戶;3.建立用戶角色;