文章出處

一些概念

一個mongod服務可以有建立多個數據庫,每個數據庫可以有多張表,這里的表名叫collection,每個collection可以存放多個文檔(document),每個文檔都以BSON(binary json)的形式存放于硬盤中,因此可以存儲比較復雜的數據類型。它是以單文檔為單位存儲的,你可以任意給一個或一批文檔新增或刪除字段,而不會對其它文檔造成影響,這就是所謂的schema-free,這也是文檔型數據庫最主要的優點。跟一般的key-value數據庫不一樣的是,它的value中存儲了結構信息,所以你又可以像關系型數據庫那樣對某些域進行讀寫、統計等操作。Mongo最大的特點是他支持的查詢語言非常強大,其語法有點類似于面向對象的查詢語言,幾乎可以實現類似關系數據庫單表查詢的絕大部分功能,而且還支持對數據建立索引。Mongo還可以解決海量數據的查詢效率,根據官方文檔,當數據量達到50GB以上數據時,Mongo數據庫訪問速度是MySQL10 倍以上。

BSON

BSON是BinaryJSON 的簡稱,是一個JSON文檔對象的二進制編碼格式。BSON同JSON一樣支持往其它文檔對象和數組中再插入文檔對象和數組,同時擴展了JSON的數據類型。如:BSON有Date類型和BinDate類型。

BSON被比作二進制的交換格式,如同Protocol Buffers,但BSON比它更“schema-less”,非常好的靈活性但空間占用稍微大一點。

BSON有以下三個特點:

1. 輕量級

2. 跨平臺

3. 效率高

命名空間

MongoDB存儲BSON對象到collections,這一系列的數據庫名和collection名被稱為一個命名空間。如同:java.util.List;用來管理數據庫中的數據。

索引

mongodb可以對某個字段建立索引,可以建立組合索引、唯一索引,也可以刪除索引,建立索引就意味著增加空間開銷。默認情況下每個表都會有一個唯一索引:_id,如果插入數據時沒有指定_id,服務會自動生成一個_id,為了充分利用已有索引,減少空間開銷,最好是自己指定一個unique的key為_id,通常用對象的ID比較合適,比如商品的ID。

 

成功啟動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”的數據庫。

數據庫常用命令

1Help查看命令提示

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; dbgetName方法是一樣的效果,都可以查詢當前使用的數據庫

9、顯示當前db狀態

db.stats();

10、當前db版本

db.version();

11、查看當前db的鏈接機器地址

db.getMongo();

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();

用戶相關

1、添加一個用戶

db.addUser("name");

db.addUser("userName", "pwd123", true); 添加用戶、設置密碼、是否只讀

2、數據庫認證、安全模式

db.auth("userName", "123123");

3顯示當前所有用戶

show users;

4、刪除用戶

db.removeUser("userName");

其他

1、查詢之前的錯誤信息

db.getPrevError();

2、清除錯誤記錄

db.resetError();

查看聚集集合基本信息

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();

聚集集合查詢

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.Login.find({},{"loginName":1}).limit(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;

索引

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();

修改、添加、刪除集合數據

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
});

updateremove其中一個是必須的參數; 其他參數可選。

參數

詳解

默認值

query

查詢過濾條件

{}

sort

如果多個文檔符合查詢過濾條件,將以該參數指定的排列方式選擇出排在首位的對象,該對象將被操作

{}

remove

若為true,被選中對象將在返回前被刪除

N/A

update

一個修改器對象

N/A

new

若為true,將返回修改后的對象而不是原始對象。在刪除操作中,該參數被忽略。

false

fields

參見Retrieving  a Subset of Fields (1.5.0+)

All fields

upsert

創建新對象若查詢結果為空。示例  (1.5.4+)

false

語句塊操作

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

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

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

4、find 游標查詢
>varcursor = db.users.find();
> while (cursor.hasNext()) { 
    printjson(cursor.next()); 
}
這樣就查詢所有的users信息,同樣可以這樣寫
varcursor = db.users.find();
while (cursor.hasNext()) { printjson(cursor.next); }
同樣可以省略{}號

5、forEach迭代循環
db.users.find().forEach(printjson);
forEach中必須傳遞一個函數來處理每條迭代的數據信息

6、將find游標當數組處理
varcursor = db.users.find();
cursor[4];
取得下標索引為4的那條數據
既然可以當做數組處理,那么就可以獲得它的長度:cursor.length();或者cursor.count();
那樣我們也可以用循環顯示數據
for (vari = 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));});

shell操作數據庫:

1. 超級用戶相關:

1. #進入數據庫admin

use admin

2. #增加或修改用戶密碼

db.addUser('name','pwd')

3. #查看用戶列表

db.system.users.find()

4. #用戶認證

db.auth('name','pwd')

5. #刪除用戶

db.removeUser('name')

6. #查看所有用戶

show users

7. #查看所有數據庫

show dbs

8. #查看所有的collection

show collections

9. #查看各collection的狀態

db.printCollectionStats()

10. #查看主從復制狀態

db.printReplicationInfo()

11. #修復數據庫

db.repairDatabase()

12. #設置記錄profiling,0=off 1=slow 2=all

db.setProfilingLevel(1)

13. #查看profiling

show profile

14. #拷貝數據庫

db.copyDatabase('mail_addr','mail_addr_tmp')

15. #刪除collection

db.mail_addr.drop()

16. #刪除當前的數據庫

db.dropDatabase()

2. 增刪改

1. #存儲嵌套的對象

db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})

2. #存儲數組對象

db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})

3. #根據query條件修改,如果不存在則插入,允許修改多條記錄

db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)

4. #刪除yy=5的記錄

db.foo.remove({'yy':5})

5. #刪除所有的記錄

db.foo.remove()

3. 索引

1. #增加索引:1(ascending),-1(descending)

2. db.foo.ensureIndex({firstname:1, lastname: 1}, {unique: true});

3. #索引子對象

4.db.user_addr.ensureIndex({'Al.Em': 1})

5. #查看索引信息

6. db.foo.getIndexes()

7. db.foo.getIndexKeys()

8. #根據索引名刪除索引

9.db.user_addr.dropIndex('Al.Em_1')

4. 查詢

1. #查找所有

2. db.foo.find()

3. #查找一條記錄

4. db.foo.findOne()

5. #根據條件檢索10條記錄

6.db.foo.find({'msg':'Hello 1'}).limit(10)

7. #sort排序

8.db.deliver_status.find({'From':'ixigua@sina.com'}).sort({'Dt',-1})

9.db.deliver_status.find().sort({'Ct':-1}).limit(1)

10. #count操作

11. db.user_addr.count()

12. #distinct操作,查詢指定列,去重復

13. db.foo.distinct('msg')

14. #”>=”操作

15.db.foo.find({"timestamp": {"$gte" : 2}})

16. #子對象的查找

17.db.foo.find({'address.city':'beijing'})

5. 管理

1. #查看collection數據的大小

2.db.deliver_status.dataSize()

3. #查看colleciont狀態

4.db.deliver_status.stats()

5. #查詢所有索引的大小

6.db.deliver_status.totalIndexSize()

5. advanced queries:高級查詢

條件操作符 $gt : > $lt : < $gte: >= $lte: <= $ne : !=、<> $in : in $nin: not in $all: all $not: 反匹配(1.3.3及以上版本)
查詢 name <> "bruce" and age >= 18 的數據 db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
查詢 creation_date > '2010-01-01' and creation_date<= '2010-12-31' 的數據 db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:newDate(2010,11,31)});
查詢 age in (20,22,24,26) 的數據 db.users.find({age: {$in: [20,22,24,26]}});
查詢 age取模10等于0 的數據 db.users.find('this.age % 10 == 0'); 或者 db.users.find({age : {$mod : [10, 0]}});
匹配所有 db.users.find({favorite_number : {$all : [6, 8]}}); 可以查詢出{name: 'David', age: 26, favorite_number: [ 6, 8,9 ] } 可以不查詢出{name: 'David', age: 26, favorite_number: [ 6, 7,9 ] }
查詢不匹配name=B*帶頭的記錄 db.users.find({name: {$not: /^B.*/}}); 查詢 age取模10不等于0 的數據 db.users.find({age : {$not: {$mod : [10, 0]}}});
#返回部分字段 選擇返回age和_id字段(_id字段總是會被返回) db.users.find({}, {age:1}); db.users.find({}, {age:3}); db.users.find({}, {age:true}); db.users.find({ name : "bruce" }, {age:1}); 0為false, 非0為true
選擇返回age、address和_id字段 db.users.find({ name : "bruce" }, {age:1, address:1});
排除返回age、address和_id字段 db.users.find({}, {age:0, address:false}); db.users.find({ name : "bruce" }, {age:0, address:false});
數組元素個數判斷 對于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ]}記錄 匹配db.users.find({favorite_number: {$size: 3}}); 不匹配db.users.find({favorite_number: {$size: 2}});
$exists判斷字段是否存在 查詢所有存在name字段的記錄 db.users.find({name: {$exists: true}}); 查詢所有不存在phone字段的記錄 db.users.find({phone: {$exists: false}});
$type判斷字段類型 查詢所有name字段是字符類型的 db.users.find({name: {$type: 2}}); 查詢所有age字段是整型的 db.users.find({age: {$type: 16}});
對于字符字段,可以使用正則表達式 查詢以字母b或者B帶頭的所有記錄 db.users.find({name: /^b.*/i});
$elemMatch(1.3.1及以上版本) 為數組的字段中匹配其中某個元素
Javascript查詢和$where查詢 查詢 age > 18 的記錄,以下查詢都一樣 db.users.find({age: {$gt: 18}}); db.users.find({$where: "this.age > 18"}); db.users.find("this.age > 18"); f = function() {return this.age > 18} db.users.find(f);
排序sort() 以年齡升序asc db.users.find().sort({age: 1}); 以年齡降序desc db.users.find().sort({age: -1});
限制返回記錄數量limit() 返回5條記錄 db.users.find().limit(5); 返回3條記錄并打印信息 db.users.find().limit(3).forEach(function(user) {print('my age is ' +user.age)}); 結果 my age is 18 my age is 19 my age is 20
限制返回記錄的開始點skip() 從第3條記錄開始,返回5條記錄(limit 3, 5) db.users.find().skip(3).limit(5);
查詢記錄條數count() db.users.find().count(); db.users.find({age:18}).count(); 以下返回的不是5,而是user表中所有的記錄數量 db.users.find().skip(10).limit(5).count(); 如果要返回限制之后的記錄數量,要使用count(true)或者count(非0) db.users.find().skip(10).limit(5).count(true);
分組group() 假設test表只有以下一條數據 { domain: "www.mongodb.org" , invoked_at: {d:"2009-11-03", t:"17:14:05"} , response_time: 0.05 , http_action: "GET /display/DOCS/Aggregation" } 使用group統計test表11月份的數據count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; db.test.group( { cond: {"invoked_at.d": {$gt: "2009-11", $lt:"2009-12"}} , key: {http_action: true} , initial: {count: 0, total_time:0} , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } , finalize: function(out){ out.avg_time = out.total_time / out.count } } );
[ { "http_action" : "GET /display/DOCS/Aggregation", "count" : 1, "total_time" : 0.05, "avg_time" : 0.05 } ]

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()