天天看點

mongodb操作使用說明應用場景操作步驟

應用場景

安裝部署完mongodb之後,需要對其進行使用,在使用過程中,對于常見操作做一個簡單彙總整理。

操作步驟

MongDB是一個高性能,開源,無模式的文檔型NosQL資料庫。

1. 主要功能特性:

1.檔案存儲格式BSON(一種json的擴充)

2.模式自由

資料格式不受限了表的結構

3.支援動态查詢

4.支援完全索引

5.支援複制(其主從複制)和故障恢複

6.使用高效的二進制資料存儲,包括大型對象

7.自動處理碎片,以支援雲計算層次的擴充。

8.支援Java、Ruby、Python、C++、PHP等多種語言

9.内部支援Javascript

2. Mongodb的優勢

1.查詢速度快

2.高并發。可以達到2萬個并發。

3.高容量。支援10TB意思的資料量

MongoDB使用場景

1.網站資料

2.緩存

3.大尺寸、低價值的資料

4.高伸縮的場景

5.用于對象以及Json資料存儲

3. Mongodb的限制

1.在32位作業系統上,不支援大于2.5G的資料

2.單個檔案大小限制16M

3.高度事務的系統

4.傳統商業智能應用

4. Mogodb和其他資料庫的差別

成功啟動MongoDB後,再打開一個指令行視窗輸入mongo,就可以進行資料庫的一些操作。

輸入help可以看到基本操作指令:

show dbs:顯示資料庫清單 
show collections:顯示目前資料庫中的集合(類似關系資料庫中的表) 
show users:顯示使用者

use <db name>:切換目前資料庫,這和MS-SQL裡面的意思一樣 
db.help():顯示資料庫操作指令,裡面有很多的指令 
db.foo.help():顯示集合操作指令,同樣有很多的指令,foo指的是目前資料庫下,一個叫foo的集合,并非真正意義上的指令 
db.foo.find():對于目前資料庫中的foo集合進行資料查找(由于沒有條件,會列出所有資料) 
db.foo.find( { a : 1 } ):對于目前資料庫中的foo集合進行查找,條件是資料中有一個屬性叫a,且a的值為1

MongoDB沒有建立資料庫的指令,但有類似的指令。

如:如果你想建立一個“myTest”的資料庫,先運作use myTest指令,之後就做一些操作(如:db.createCollection('user')),這樣就可以建立一個名叫“myTest”的資料庫。           

5. 資料庫常用指令

1、Help檢視指令提示
help
db.help();
db.yourColl.help();
db.youColl.find().help();
rs.help();

2、切換/建立資料庫
use yourDB; 當建立一個集合(table)的時候會自動建立目前資料庫

3、查詢所有資料庫
show dbs;

4、删除目前使用資料庫
db.dropDatabase();

5、從指定主機上克隆資料庫
db.cloneDatabase(“127.0.0.1”); 将指定機器上的資料庫的資料克隆到目前資料庫

6、從指定的機器上複制指定資料庫資料到某個資料庫
db.copyDatabase("mydb", "temp", "127.0.0.1");将本機的mydb的資料複制到temp資料庫中

7、修複目前資料庫
db.repairDatabase();

8、檢視目前使用的資料庫
db.getName();
db; db和getName方法是一樣的效果,都可以查詢目前使用的資料庫

9、顯示目前db狀态
db.stats();

10、目前db版本
db.version();

11、檢視目前db的連結機器位址
db.getMongo();           

6. Collection聚集集合

1、建立一個聚集集合(table)
db.createCollection(“collName”, {size: 20, capped: 5, max: 100});

2、得到指定名稱的聚集集合(table)
db.getCollection("account");

3、得到目前db的所有聚集集合
db.getCollectionNames();

4、顯示目前db所有聚集索引的狀态
db.printCollectionStats();           

7. 使用者相關

1、添加一個使用者
db.addUser("name");
db.addUser("userName", "pwd123", true); 添加使用者、設定密碼、是否隻讀

2、資料庫認證、安全模式
db.auth("userName", "123123");

3、顯示目前所有使用者
show users;

4、删除使用者
db.removeUser("userName");           

8. 其他

1、查詢之前的錯誤資訊
 db.getPrevError();
2、清除錯誤記錄
 db.resetError();           

9. 檢視聚集集合基本資訊

1、檢視幫助 db.yourColl.help();
2、查詢目前集合的資料條數 db.yourColl.count();
3、檢視資料空間大小 db.userInfo.dataSize();
4、得到目前聚集集合所在的db db.userInfo.getDB();
5、得到目前聚集的狀态 db.userInfo.stats();
6、得到聚集集合總大小 db.userInfo.totalSize();
7、聚集集合儲存空間大小 db.userInfo.storageSize();
8、Shard版本資訊 db.userInfo.getShardVersion()
9、聚集集合重命名 db.userInfo.renameCollection("users"); 将userInfo重命名為users
10、删除目前聚集集合 db.userInfo.drop();           

10. 聚集集合查詢

1、查詢所有記錄
db.userInfo.find();
相當于:select* from userInfo;
預設每頁顯示20條記錄,當顯示不下的情況下,可以用it疊代指令查詢下一頁資料。注意:鍵入it指令不能帶“;”
但是你可以設定每頁顯示資料的大小,用DBQuery.shellBatchSize= 50;這樣每頁就顯示50條記錄了。

2、查詢去掉後的目前聚集集合中的某列的重複資料
db.userInfo.distinct("name");
會過濾掉name中的相同資料
相當于:select distict name from userInfo;

3、查詢age = 22的記錄
db.userInfo.find({"age": 22});
相當于: select * from userInfo where age = 22;

4、查詢age > 22的記錄
db.userInfo.find({age: {$gt: 22}});
相當于:select * from userInfo where age >22;

5、查詢age < 22的記錄
db.userInfo.find({age: {$lt: 22}});
相當于:select * from userInfo where age <22;

6、查詢age >= 25的記錄
db.userInfo.find({age: {$gte: 25}});
相當于:select * from userInfo where age >= 25;

7、查詢age <= 25的記錄
db.userInfo.find({age: {$lte: 25}});

8、查詢age >= 23 并且 age <= 26
db.userInfo.find({age: {$gte: 23, $lte: 26}});

9、查詢name中包含 mongo的資料
db.userInfo.find({name: /mongo/});
//相當于%%
select * from userInfo where name like ‘%mongo%’;

10、查詢name中以mongo開頭的
db.userInfo.find({name: /^mongo/});
select * from userInfo where name like ‘mongo%’;

11、查詢指定列name、age資料
db.userInfo.find({}, {name: 1, age: 1});
相當于:select name, age from userInfo;
當然name也可以用true或false,當用ture的情況下河name:1效果一樣,如果用false就是排除name,顯示name以外的列資訊。

12、查詢指定列name、age資料, age > 25
db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
相當于:select name, age from userInfo where age >25;

13、按照年齡排序
升序:db.userInfo.find().sort({age: 1});
降序:db.userInfo.find().sort({age: -1});

14、查詢name = zhangsan, age = 22的資料
db.userInfo.find({name: 'zhangsan', age: 22});
相當于:select * from userInfo where name = ‘zhangsan’ and age = ‘22’;

15、查詢前5條資料
db.userInfo.find().limit(5);
相當于:selecttop 5 * from userInfo;

16、查詢10條以後的資料
db.userInfo.find().skip(10);
相當于:select * from userInfo where id not in (
selecttop 10 * from userInfo
);

17、查詢在5-10之間的資料
db.userInfo.find().limit(10).skip(5);
可用于分頁,limit是pageSize,skip是第幾頁*pageSize

18、or與 查詢
db.userInfo.find({$or: [{age: 22}, {age: 25}]});
相當于:select * from userInfo where age = 22 or age = 25;

19、查詢第一條資料
db.userInfo.findOne();
相當于:selecttop 1 * from userInfo;
db.userInfo.find().limit(1);

20、查詢某個結果集的記錄條數
db.userInfo.find({age: {$gte: 25}}).count();
相當于:select count(*) from userInfo where age >= 20;

21、按照某列進行排序
db.userInfo.find({sex: {$exists: true}}).count();
相當于:select count(sex) from userInfo;           

11. 索引

1、建立索引
db.userInfo.ensureIndex({name: 1});
db.userInfo.ensureIndex({name: 1, ts: -1});

2、查詢目前聚集集合所有索引
db.userInfo.getIndexes();

3、檢視總索引記錄大小
db.userInfo.totalIndexSize();

4、讀取目前集合的所有index資訊
db.users.reIndex();

5、删除指定索引
db.users.dropIndex("name_1");

6、删除所有索引索引
db.users.dropIndexes();           

12. 修改、添加、删除集合資料

1、添加
db.users.save({name: ‘zhangsan’, age: 25, sex: true});
添加的資料的資料列,沒有固定,根據添加的資料為準

2、修改
db.users.update({age: 25}, {$set: {name: 'changeName'}}, false, true);
相當于:update users set name = ‘changeName’ where age = 25;

db.users.update({name: 'Lisi'}, {$inc: {age: 50}}, false, true);
相當于:update users set age = age + 50 where name = ‘Lisi’;

db.users.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'hoho'}}, false, true);
相當于:update users set age = age + 50, name = ‘hoho’ where name = ‘Lisi’;

3、删除
db.users.remove({age: 132});

4、查詢修改删除
db.users.findAndModify({
 query: {age: {$gte: 25}}, 
 sort: {age: -1}, 
 update: {$set: {name: 'a2'}, $inc: {age: 2}},
 remove: true
});

db.runCommand({ findandmodify : "users", 
 query: {age: {$gte: 25}}, 
 sort: {age: -1}, 
 update: {$set: {name: 'a2'}, $inc: {age: 2}},
 remove: true
});
update 或 remove 其中一個是必須的參數; 其他參數可選。           

13. 語句塊操作

1、簡單Hello World
print("Hello World!");
這種寫法調用了print函數,和直接寫入"Hello World!"的效果是一樣的;

2、将一個對象轉換成json
tojson(new Object());
tojson(new Object('a'));

3、循環添加資料
> for (var i = 0; i < 30; i++) {
... db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
... };
這樣就循環添加了30條資料,同樣也可以省略括号的寫法
> for (var i = 0; i < 30; i++) db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
也是可以的,當你用db.users.find()查詢的時候,顯示多條資料而無法一頁顯示的情況下,可以用it檢視下一頁的資訊;

4、find 遊标查詢
>var cursor = db.users.find();
> while (cursor.hasNext()) { 
 printjson(cursor.next()); 
}
這樣就查詢所有的users資訊,同樣可以這樣寫
var cursor = db.users.find();
while (cursor.hasNext()) { printjson(cursor.next); }
同樣可以省略{}号

5、forEach疊代循環
db.users.find().forEach(printjson);
forEach中必須傳遞一個函數來處理每條疊代的資料資訊

6、将find遊标當數組處理
var cursor = db.users.find();
cursor[4];
取得下标索引為4的那條資料
既然可以當做數組處理,那麼就可以獲得它的長度:cursor.length();或者cursor.count();
那樣我們也可以用循環顯示資料
for (var i = 0, len = c.length(); i < len; i++) printjson(c[i]);

7、将find遊标轉換成數組
> var arr = db.users.find().toArray();
> printjson(arr[2]);
用toArray方法将其轉換為數組

8、定制我們自己的查詢結果
隻顯示age <= 28的并且隻顯示age這列資料
db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);
db.users.find({age: {$lte: 28}}, {age: true}).forEach(printjson);
排除age的列
db.users.find({age: {$lte: 28}}, {age: false}).forEach(printjson);

9、forEach傳遞函數顯示資訊
db.things.find({x:4}).forEach(function(x) {print(tojson(x));});