Mongodb數據庫使用

一、啓動MongoDB

1.服務器啓動方式:

mongod --dbpath=c:\db --logpath=c:\mongo\logs\mongodb.log

dbpath爲數據庫本地位置

logpath爲日誌輸出位置(可以省略)


注:本地位置需要手動創建


2.客戶端啓動方式

mongo localhost:27017

27017爲服務器端默認啓動端口;


3.可以採用更加系統化的配置方式:[linux環境]

cat /etc/mongodb.cnf
dbpath=/data/db/

啓動客戶端的時候:

mongod -f /etc/mongodb.cnf

4.Daemon模式啓動


在服務器端啓動代碼的最後加上 --fork


但是,好像window端無法使用;而且mac上卻可以,也許是window不支持;


二、插入記錄

a={name:"will"};

如上代碼,Mongodb的數據格式類似json,而插入數據的方式如下:

db.things.save(a);

可以通過下面代碼查看數據:

db.things.find();

注:

1.Mongodb在插入數據之前不需要預先創建集合,在第一插入數據時候自動創建(容易出錯)

2.可以存儲任何結構的數據

3.每次插入的時候都會有一個ID 叫做_id


注:

Mongodb可以採用js的編程語法遍歷數據,如下代碼:

for(var i=0;i<10;i++)db.things.save({x:4,j:i});

可以使用這樣的語句插入


三、查詢方式

普通查詢:

1.

var cursor = db.things.find();
while(cursor.hasNext())printjson(cursor.next());
printjson(cursor[4]);

2.

db.things.find().forEach(printjson());

3.

var arr = db.things.find().toArray();


條件查詢:

1.db.things.find({name:"will"})

2.findOne():只返回遊標的第一條數據

3.限制limit

db.things.find().limit(4);


四、修改記錄

db.things.update({name:"will"},{$set:{name:"will_new"}});


五、刪除記錄

db.things.remove();

六、高級查詢

1.條件操作符

$lt    <
$lte   <=
$gt    >
$gte   >=

例如:db.collection.find({"field":{$gt:value}});


2.$all 匹配滿足所有[]內的數據

db.collection.find({age:{$all:[6,8]}});


3.$exists 判斷字符是否存在

db.collection.find({age:{$exists:true}});//所有存在age字段的記錄
db.collection.find({age:{$exists:false}});//所有不存在age字段的記錄

4.Null值處理

db.collection.find({age:null});


注:null和不存在不一樣;


5.$mod 取模運算

db.collection.find({age:{$mod[6,1]}});//查詢age取模6等於1的數據

6.$ne 不等於

db.collection.find({age:{$ne:7}});//查詢age不等於7的

7.$in 包含 $nin 不包含

db.collection.find({age:{$in:[7,8]}});//查詢age在7 8之間的


8.$size 數組元素個數

{name:"will",xxx:[1,2,3]};
db.collection.find({xxx:{$size:3}});


9.支持正則表達式


10.count 查詢記錄條數

db.collection.find().count();
db.collection.count();

11.skip限制記錄起點

db.collection().skip(5).limit(3)

12.sort 排列

db.collection().sort({age:1});//升序 asc
db.collection().sort({age:-1});//降序 desc


七、遊標

for(var i = db.collection.find();c.hasNext();){
     c.next();
}

八、存儲過程

用js支持存儲過程,這部分沒有學習 就不做總結了



















發佈了38 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章