主要進程
mongod.exe爲啓動數據庫實例的進程。
mongo是一個與mongod進程進行交互的JavaScript shell進程,它提供了一些交互的接口函數用戶對數據庫的管理。
基本命令
show databases; 查詢數據庫列表
show collections; 查詢所有的集合 對應關係型數據庫的表
use test; 數據庫切換 切換到test數據庫
mongodb數據庫記錄成爲文檔
插入文檔命令
db.customers.save({name:"張三",age:15,address:'北京東城"}); 向集合customer庫插入一個文檔
for(var i=1;i<=100;i++) db.customers.save({name:"張三"+i,age:i,telephone:"1861400275"+i}); 批量插入100個文檔
查詢選擇器
db.customers.find();
db.customers.find({name:"張三11'});
db.customers.find({age:{$lt:45}}); 關鍵字 $lt less than 小於
$lte 小於等於 less than equals
$gt 大於 greater than
$gte 大於等於 greate than equals
db.customer.find({age:{$lt:45,$gt:35}});
db.customer.find({age:{$in:[34,35,36]}}); $in 值在範圍內 $nin 值不在範圍內
db.customer.find({age:{$ne:50}}); $ne 關鍵字的值不等於
db.customer.find({$or:[{age:{$lt:5},{name:"zhangsan"}}]}); $or 或 age小於5或name等於zhangsan
db.customer.find({$and:[{age:{$lt:5},{name:"zhangsan"}}]}); $and 且 兩個條件同時滿足
db.customer.find({id:{$exists:false}}); 等價於 db.customer.find({id:null});
MongoDB表結構是不固定的,有時需要返回包含某個字段的所有記錄或不包含的
查詢投射
查詢的結果集返回指定的字段
db.customer.find({age:{$lt:10}},{_id:0,id:1,name:1}); _id:0 表示不返回_id
第一個{}內爲查詢選擇器,第二個{}爲對前面返回的結果集進行進一步過濾的條件,即投射項。
db.customer.find().skip(10).limit(5).sort(id:-1); 跳過前十條,取五條,id:-1表示降序排列
數組操作
文檔的屬性爲數組 AttributeValue:["收腰型","修身型","直筒型","寬鬆型"]
db.DictGoodsAttribute.find({"AtributeValue":"收腰型"}); 只要屬性中包含該值,就能返回
匹配數組中指定位置的元素值
db.DictGoodsAttribute.find({"AttributeValue.0":"收腰型"}); 第一個屬性值爲"收腰型"
增該刪操作
增加記錄 db.customer.save();
1.第一次插入數據時,不需要預先創建集合,插入數據時會自動創建
2.插入時會默認創建主鍵_id,類型爲ObjectId類型,這樣設計爲了更好地支持分佈式存儲
3._id插入時複製不能重複
修改語句 條件 賦值
db.customer.update(query,update,<upsert>,<multi>);
query爲過濾條件 update爲賦值 若只包含字段,不包含操作項,則會發生取代性更改
upsert 可選參數 boolean類型 默認爲false,更新匹配記錄,找不到則插入新的文檔到集合,插入新記錄
multi 可選參數 boolean類型 默認爲false,更新匹配到的第一個文檔,當爲true時,更新所有匹配的文檔
db.customer.update({id:5},{$set:{name:"zhangsan"}},{upsert:true},{multi:true});
刪除語句
db.customer.remove({name:"zhangsan"}); 刪除所有 name:zhangsan的文檔
db.customer.remove({name:"zhangsan"},1); 刪除第一個匹配文檔
db.customer.remove({}); 刪除所有文檔,但不刪除對應的索引集合,文檔對象也會從相應的數據文件中刪去
索引
和關係型數據庫一樣,索引的主要作用:提高數據獲取的性能
MongodDB的數據結構也是B+樹
單字段索引
db.customer.ensuerIndex({name:1},{unique:true}); 字段name創建索引,unique 說明是唯一索引
唯一索引創建成功後,會在相應的數據庫系統集合system.indexes增加一條索引記錄
db.system.indexes.find() 查看所有索引
db.customer.find({name:"zhangsan"}).explain();可以使用explain()查詢分析函數查看增加索引後查詢比較
符合索引
db.customer.find({name:1,age:1}); 在兩個字段上進行索引
未使用索引,選擇器 explain函數解析結果
在字段name上添加索引,explain解析結果
對一個值爲數組類型的字段創建索引,默認對數組中的每一個元素創建索引
AttributeValue:["0-99","100-299","300-499"] 此時創建的索引爲所有元素索引
元素爲嵌套文檔 statusInfo:[{status:9,desc:"已取消"},{status:10,desc:"已發貨"}]
爲單個字段創建索引 ensureIndex({"statusInfo.desc":1});
索引的刪除
db.customer.dropIndex("_name"); 參數爲索引名