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':'[email protected]','Al':['[email protected]','[email protected]']})

         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:

猜你喜欢

转载自blog.csdn.net/lhdsjhuang/article/details/77696351