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”;

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”;


刪:
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)    //批量更新所有匹配的數據;

注:mongodb默認只更新查找到的第一條數據,目的是防止update誤操作;


查:
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”進行排序;


二、索引


增:
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索引


三、mongoDB安全:


1.開啓權限認證;
2.創建用戶;
3.創建用戶角色;



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章