RockMongo 查询条件小结

一、常见的查询情况
1.简单查询

//xid=560870 and type=video
{
"xid": 560870,
"type": "video"
}

//查询数组中的数据
array(
"fruit.name"=>'aa'
)

返回如:

array (
  'fruit' => 
  array (
    'name' => 'aa',
    'age' => '34',
  ),
  'name' => 'caihuafeng',
)

2.模糊查询

//content like %爱%
array(
"content"=>new MongoRegex("/爱/i")
)

//查询以"爱"开头并且以"爱"结尾的数据
array(
"content"=>new MongoRegex("/^爱$/i")
)

3.大于、小于、不等于查询

//uid>=561484
array(
"uid"=>array('$gte'=>561484)
)

//uid>=0 and uid<=561484
array(
"uid"=>array('$gte'=>0,'$lte'=>561484)
)

//uid in (561484,0)
array(
"uid"=>array('$in'=>array(561484,0))
)

说明:

$gt   >
$gte  >=
$lt   <
$lte  <=
$ne   !=
$in : in 
$nin: not in 
$all: all 
$not: 反匹配

4.查询指定字段

//查询存在uid字段的数据
array(
"uid"=>array('$exists'=>true)
)

//查询不存在uid字段的数据
array(
"uid"=>array('$exists'=>false)
)

5.查询字段类型

//查询content字段为字符型的数据
array(
"content"=>array('$type'=>2)
)

6.查询数组指定的长度

//查询fruit大小为2的数据
array(
"fruit"=>array('$size'=>2)
)

返回如下:

array (
  '_id' => new MongoId("4e411abf7c1883973c0e2114"),
  'fruit' => 
      array (
        '0' => 'aa',
        '1' => 'bb',
      ),
  'name' => 'caihuafeng',
)

7.插入多条测试数据

> for(i=1;i<=1000;i++){
... db.blog.insert({"title":i,"content":"mongodb测试文章。","name":"刘"+i});                                                      
... }
db.blog.list.find().limit(10).forEach(function(data){print("title:"+data.title);})   // 循环forEach 用法
db.blog.findOne();  // 取一条数据
db.blog.find();     // 取多条数据
db.blog.remove();   // 删除数据集 
db.blog.drop();     // 删除表

二、常见的查询操作

db.blog.find()           // 相当于select * from blog 
db.blog.find({"age":27}) // 相当于select * from blog where age='27'
db.blog.find({"age":27,"name":"xing"}) // 相当于select * from blog where age='27' and name="xing"
db.blog.find({},{"name":1})       // select name from blog ,如果name:0则是不显示name字段
db.blog.find().limit(1)           // 相当于select * from blog limit 1
db.blog.find().skip(10).limit(20) // 相当于select * from blog limit 10,20

1) skip用的时候,一定要注意要是数量多的话skip就会变的很慢,所有的数据库都存在此问题,可以不用skip进行分页,用最后一条记录做为条件

db.blog.find({"age":{"$gte":18,"$lte":30}})     
select * from blog  where age>=27 and age<=50
$gt   >
$gte  >=
$lt   <
$lte  <=
$ne   !=
$in : in 
$nin: not in 
$all: all 
$not: 反匹配
//查询creation_date > '2010-01-01' and creation_date <= '2010-12-31'的数据 
db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
db.blog.find().sort({_id:-1})                      // 相当于select * from blog  order by _id desc  按_id倒序取数据  1为正序,多个条件用,号分开如{name:1,age:-1}
db.blog.find({"_id":{"$in",[12,3,100]}})          // 相当于select * from blog where _id in (12,3,100)
db.blog.find({"_id":{"$nin",[12,3,100]}})         // 相当于select * from blog where _id not in (12,3,100)
db.blog.find({"$or":[{"age":16},{"name":"xing"}]}) // 相当于select * from blog where age = 16 or name = 'xing'
db.blog.find({"id_num":{"$mod":[5,1]}})           // 取的是id_num mod 5 = 1 的字段,如id_num=1,6,11,16
db.blog.find({"id_num":{"$not":{"$mod":[5,1]}}})   // 取的是id_num mod 5 != 1 的字段,如除了id_num=1,6,11,16等所有字段,多于正则一起用

2) $exists判断字段是否存在

db.blog.find({ a : { $exists : true }});  // 如果存在元素a,就返回
db.blog.find({ a : { $exists : false }}); // 如果不存在元素a,就返回

3) $type判断字段类型
查询所有name字段是字符类型的

db.users.find({name: {$type: 2}}); 

4) 查询所有age字段是整型的

db.users.find({age: {$type: 16}}); 
db.blog.find({"z":null})        // 返回没有z字段的所有记录
db.blog.find({"name":/^joe/i})  // 查找name=joe的所有记录,不区分大小写
db.blog.distinct('content')     // 查指定的列,并去重

5) 查询数组

db.blog.find({"fruit":{"$all":["苹果","桃子","梨"]}})   // fruit中必需有数组中的每一个才符合结果
db.blog.find({"fruit":{"$size":3}})  // fruit数组长度为3的符合结果
db.blog.find({"$push":{"fruit":"桔子"}})// 相当于db.blog.find({"$push":{"fruit":"桔子"},"$inc":{"size":1}})
//$slice // 可以按偏移量返回记录,针对数组。如{"$slice":10}返回前10条,{"$slice":{[23,10]}}从24条取10

如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素

db.people.find({"name.first":"joe","name.last":"schmoe"}) 
// 子查询如:
{"id":34,"name":{"first":"joe","last":"schmoe"}}
db.blog.find({"comments":{"$elemMatch":{"author":"joe","score":{"$gte":5}}}}) 
// 查joe发表的5分以上的评论,注意comments为二维数组
// $where 在走投无路的时候可以用,但它的效率是很低的。

6) 游标用法
cursor.hasNext()检查是否有后续结果存在,然后用cursor.next()将其获得。

>while(cursor.hasNext()){
   var obj = cursor.next();
   //do same
}
> use blog
> db.blog.insert({"title":"华夏之星的博客","content":"mongodb测试文章。"});
> db.blog.find();
{ "_id" : ObjectId("4e29fd262ed6910732fa61df"), "title" : "华夏之星的博客", "content" : "mongodb测试文章。" }
> db.blog.update({title:"华夏之星的博客"},{"author":"星星","content":"测试更新"});
> db.blog.find();
{ "_id" : ObjectId("4e29fd262ed6910732fa61df"), "author" : "星星", "content" : "测试更新" }
db.blog.insert // 不带括号则显示源码
db.blog.insert();// 插入
db.blog.update();// 更新
> db.blog.update({title:"华夏之星的博客"},{"author":"星星","content":"测试更新"});

7) update默认情况下只能对符合条件的第一个文档执行操作,要使所有的匹配的文档都得到更新,可以设置第四个参数为 true

> db.blog.update({title:"华夏之星的博客"},{"author":"星星","content":"测试更新"},false,true);
> db.runCommand({getLastError:1}) // 可以查看更新了几条信息,n就是条数

8) 备份blog数据库到/soft目录(备份出来的数据是二进制的,已经经过压缩。)
-d 数据库
-c 表

/usr/local/webserver/mongodb/bin/mongodump -h 127.0.0.1 -port 27805 -d comment -o /soft/

还原数据库单张表

> /usr/local/webserver/mongodb/bin/mongorestore -h 127.0.0.1 -port 27805
> -d comment -c comment_video   /soft/comment/comment_video.bson

还原数据库

/usr/local/webserver/mongodb/bin/mongorestore -h 127.0.0.1 -port 27805 --directoryperdb /soft/comment

9) $all
$all和$in类似,但是他需要匹配条件内所有的值:
如有一个对象:
{ a: [ 1, 2, 3 ] }
下面这个条件是可以匹配的:

db.things.find( { a: { $all: [ 2, 3 ] } } );

但是下面这个条件就不行了:

db.things.find( { a: { $all: [ 2, 3, 4 ] } } );6) $size

10) $size是匹配数组内的元素数量的,如有一个对象:{a:[“foo”]},他只有一个元素:
下面的语句就可以匹配:

db.things.find( { a : { $size: 1 } } );

官网上说不能用来匹配一个范围内的元素,如果想找$size<5之类的,他们建议创建一个字段来保存元素的数量。

11) $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。

db.things.find( { a : { $type : 2 } } ); // matches if a is a string
db.things.find( { a : { $type : 16 } } ); // matches if a is an int

12)正则表达式
mongo支持正则表达式,如:
db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写10) 查询数据内的值
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。db.things.find( { colors : “red” } );
13) $elemMatch
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:

> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) 
{ "_id" : ObjectId("4b5783300334000000000aa9"), 
"x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
}$elemMatch : { a : 1, b : { $gt : 1 } }

所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。

> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )

$elemMatch是匹配{ “a” : 1, “b” : 3 },而后面一句是匹配{ “b” : 99 }, { “a” : 11 }
14) 查询嵌入对象的值

db.postings.find( { "author.name" : "joe" } );

注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:

> db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
// 如果我们要查询 authors name 是Jane的, 我们可以这样:
> db.blog.findOne({"author.name" : "Jane"})

三、mongodb同其他数据一样,提供索引,来提高查询的效率。看下索引的种类:
1:基础索引
2:文档索引
3:组合索引
4:唯一索引

基础索引:

比如一个post集合中含有name字段,在name字段上建立索引:

db.post.ensureIndexe({name:1})    

后面的1意思是升序,-1表示降序
查询该集合的索引:

db.post.getIndexes();

会显示出索引的名字等等信息
如果在一个很大的字段上建立索引的话,那么就要注意,因为建立索引是很耗时间的,而且要锁住集合,不能写,所以建立大的索引要慎重,可以放在后台执行:

db.post.ensureIndexe({name:1},{backgroud:true})

删除索引:

db.post.dropIndexes()  ----删除post上面所有索引

db.post.dropIndex({name:1})     ------删除指定的单个索引

文档索引:

也就是说字段可以是一个文档:

db.post.insert({name:"documents",address:{city:"hangzhou",stat:"HZ"}})

可以在address字段建议索引:

db.post.ensureIndexe({address:1})

那么我们在查询的时候就会用到这个索引:

db.post.find({address:{city:"hangzhou",stat:"HZ"}})

但是如果db.post.find({address:{stat:”HZ”,city:”hangzhou”}})则不走该索引,因为里面的顺序不一样。

组合索引:

post集合里面有name,和sga字段:

db.post.ensureIndex({name:1,age:1})

这就是一个简单的组合索引

所以在以name为开始查询,或者排序都可以用到该索引 ,这里1或者-1主要关系到范围查询和排序的时候是否用到

唯一索引:

看个例子就明白,和其他数据库的性质一样,不能存在重复值

db.post.ensurIndex({name:1,age:1},{unique:true})

如果有重复的值,那么无法建立唯一索引,会报错:E11000
强制使用索引(hint)

> db.t5.insert({name: "zhanghaihong",age: 20})
> db.t5.ensureIndex({name:1, age:1})
> db.t5.find({age:{$lt:30}}).explain()
{
        "cursor" : "BasicCursor",
        "indexBounds" : [ ],
        "nscanned" : 1,
        "nscannedObjects" : 1,
        "n" : 1,
        "millis" : 0,
        "allPlans" : [
                {
                        "cursor" : "BasicCursor",
                        "indexBounds" : [ ]          ----可以看到没有使用索引,此处没有任何东西
                }
        ]
}

db.t5.find({age:{$lt:30}}).hint({name:1, age:1}).explain()    ---红色部分强制使用索引

{
        "cursor" : "BtreeCursor name_1_age_1",
        "indexBounds" : [                                 ---使用了索引
                [
                        {
                                "name" : {
                                        "$minElement" : 1
                                },
                                "age" : -1.7976931348623157e+308
                        },
                        {
                                "name" : {
                                        "$maxElement" : 1
                                },
                                "age" : 30
                        }
                ]
        ],
        "nscanned" : 1,
        "nscannedObjects" : 1,
        "n" : 1,
        "millis" : 0
}

MongoDB手册

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章