Mongodb基本知識和常用語法


from: http://blog.csdn.net/q383965374/article/details/8509153?reload  the author write a grate article

推薦閱讀:《MongoDB:The Definitive Guide》 http://book.douban.com/subject/4746684/

                     中文版名《MongoDB權威指導》

 

參考:http://huangz.iteye.com/blog/997120  (對mongodb有詳細的介紹)

               http://henghengdh.iteye.com/blog/1752846(常用命令)

         http://www.2cto.com/database/201202/119912.html(常用命令)

 

數據結構:

簡單的說:   1. 文檔(document)是MongoDB中最基本的數據組織形式,每個文檔以Key-Value(鍵-值對)的方式組織起來

                        例如:

[javascript]  view plain copy
 
  1. {"greeting" : "Hello World!"}  

                       2. 一個文檔可以有多個Key-Value組合,每個Value可以是不同的類型,比如String、Integer、List等等

                      例如:

[html]  view plain copy
 
  1. 1.{ "name" : "huangz",     
  2. 2.   "sex" : "male",     
  3. 3.   "age" : 20 }  

                       3.將多個文檔組織起來,就形成了集合(collection)。如果將文檔比作關系數據庫中的行(row)的話,那么集合就是數據庫中的表(table)。

在關系數據庫(如MySQL)中,在同一個數據庫表里面,總是有相同的行(row),比如你有一個student表,里面有id,name,age,class,grade幾個row,那么整個student只能有相同的幾個行。

 

但是在MongoDB當中,內容格式可以很隨意,在一個集合中,儲存多個有不同Key、不同類型的文檔,比如你可以在一個student集合里面,有如下格式的文檔:

 在這個student集合里面,並不要求每個文檔都要有同樣的Key和同樣的類型,一切隨意。

[javascript]  view plain copy
 
  1. 1.{     
  2. 2.    "name" : "huangz",     
  3. 3.    "age" : 20,     
  4. 4.    "sex" : "male"    
  5. 5.}     
  6. 6.    
  7. 7.{       
  8. 8.    "name" : "jack",     
  9. 9.    "class" : 3,     
  10. 10.    "grade" : 3     
  11. 11.}    

 

總結起來,MongoDB組織數據的方式如下:
 
Key-Value對 > 文檔 > 集合 > 數據庫

另外, 在MongoDB中(不包括GridFS),單個文檔大小不得超過4mb(版本>=1.7則是16MB)。

 

 

                    Key的遵循以下規則:

  • "\0"不能使用
  • 帶有"."號,"_"號和"$"號前綴的Key被保留
  • 大小寫有區別,Age不同於age
  • 同一個文檔不能有相同的Key
  • 除了上面幾條規則外,其他所有UTF-8字符都可以使用 

集合的命名規則和文檔的命名規則大概相似,另外要記住的是

  • system集合是被保留的

另外,“.”號的使用在集合當中是允許的,它們被成為子集合(Subcollection);比如你有一個blog集合,你可以使用blog.title,blog.content或者blog.author來幫組你更好地組織集合。

 

將多個集合組織起來,就形成了數據庫(database)。單個MongoDB實例可以使用多個數據庫,每個數據庫都是獨立運作的,可以有單獨的權限,每個數據庫的數據被分開保存在不同的文件里。

 

數據庫也有命名規則:

  • 不能使用空字符""或者空格" "、點號"."、美元符"$"、斜線"/"、反斜線"\"和"\0"
  • 只能用小寫
  • 必須少於64個字節(byte)
 
數據類型:
[javascript]  view plain copy
 
  1. 1./* 空值 null */    
  2. 2.    
  3. 3.{ "name" : null }     
  4. 4.    
  5. 5./* 布爾值 boolean */    
  6. 6.    
  7. 7.{ "flag" : true }     
  8. 8.    
  9. 9./* 數值   
  10. 10.    包括32bit、64bit整數integer類型和64bit浮點floating point類型 */    
  11. 11.    
  12. 12.{     
  13. 13.  "copies" : 300,     
  14. 14.  "price" : 60.8     
  15. 15.}     
  16. 16.    
  17. 17./* 字符串 string */    
  18. 18.    
  19. 19.{ "dbname" : "MongoDB" }     
  20. 20.    
  21. 21./* 日期 date */    
  22. 22.    
  23. 23.{ "post_time" : new Date() }     
  24. 24.    
  25. 25./* 正則表達式 regular expression */    
  26. 26.    
  27. 27.{ "name_match" : /huangz/i }     
  28. 28.    
  29. 29./* 數組類型 array */    
  30. 30.    
  31. 31.{ "tags" : ["mongodb""nosql"] }     
  32. 32.    
  33. 33./* 嵌套文檔 embedded document    
  34. 34.    一個文檔里面Key的值可以是另外一個文檔 */    
  35. 35.    
  36. 36.{     
  37. 37.  "name" : "huangz",     
  38. 38.  "phone" : { "home" : 123321,     
  39. 39.                     "mobile" :  15820123123}     
  40. 40.}     
  41. 41.    
  42. 42./* id   
  43. 43.    每個MongoDB文檔都必須有一個叫作"_id"的Key, 同一集合里面的文檔_id必須各不相同。   
  44. 44.    id可以在創建文檔的時候指定,可以是任何類型,無指定時,默認使用ObjectId對象,自動生成不同的id。   
  45. 45.  
  46. 46.    ObjectId對象生成id(12位)的規則如下:   
  47. 47.        0-3 : Timestamp,時間撮   
  48. 48.        4-6  :  Machine,機器代碼   
  49. 49.        7-8  :  PID,MongoDB的程序id   
  50. 50.        9-11:  Increment,一個自增量   
  51. 51.*/    
  52. 52.    
  53. 53.{ "_id" : ObjectId("4da025ac5149e6d915098c59"), "name" : "huangz""phone" : { "home" : 33123123, "mobile" : 15820123123 } }    
常用命令:
 
shell操作數據庫: 

   1.  超級用戶相關: 

         1. #進入數據庫admin 

use admin 

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

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


         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')
         db.copyDatabase("mydb", "temp", "127.0.0.1");
         將本機的mydb的數據復制到temp數據庫中


        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. 查詢 
 

條件操作符 
$gt : > 
$lt : < 
$gte: >= 
$lte: <= 
$ne : !=、<> 
$in : in 
$nin: not in 
$all: all
$or:or
$not: 反匹配(1.3.3及以上版本)
模糊查詢用正則式


1、查詢所有記錄
db.userInfo.find();
相當於:select * from userInfo;
 
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);
相當於:select top 5 * from userInfo;
 
16、查詢10條以后的數據
db.userInfo.find().skip(10);
相當於:select * from userInfo where id not in (
select top 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();
相當於:select top 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;
 
 
22、查詢 age取模10等於0 的數據 
db.users.find('this.age % 10 == 0'); 
或者 
db.users.find({age : {$mod : [10, 0]}}); 

23、匹配所有 
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 ] } 

24、查詢不匹配name=B*帶頭的記錄 
db.users.find({name: {$not: /^B.*/}}); 
查詢 age取模10不等於0 的數據 
db.users.find({age : {$not: {$mod : [10, 0]}}}); 

25、返回部分字段 
選擇返回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 

26、排除返回age、address和_id字段 
db.users.find({}, {age:0, address:false}); 
db.users.find({ name : "bruce" }, {age:0, address:false}); 

27、數組元素個數判斷 
對於{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }記錄 
匹配db.users.find({favorite_number: {$size: 3}}); 
不匹配db.users.find({favorite_number: {$size: 2}}); 

28、$exists判斷字段是否存在 
查詢所有存在name字段的記錄 
db.users.find({name: {$exists: true}}); 
查詢所有不存在phone字段的記錄 
db.users.find({phone: {$exists: false}}); 

29、$type判斷字段類型 
查詢所有name字段是字符類型的 
db.users.find({name: {$type: 2}}); 
查詢所有age字段是整型的 
db.users.find({age: {$type: 16}}); 

30、對於字符字段,可以使用正則表達式
查詢以字母b或者B帶頭的所有記錄 
db.users.find({name: /^b.*/i}); 
{"Name":/中鐵/}

31、$elemMatch(1.3.1及以上版本) 
為數組的字段中匹配其中某個元素 

32、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); 

33、限制返回記錄的開始點skip() 
從第3條記錄開始,返回5條記錄(limit 3, 5) 
db.users.find().skip(3).limit(5); 

34、查詢記錄條數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); 

  
 
5. 管理 

         1. #查看collection數據的大小 

          db.deliver_status.dataSize() 

         2. #查看colleciont狀態 

         db.deliver_status.stats() 

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

         db.deliver_status.totalIndexSize() 

for more:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM