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手冊

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