MongoDB 常用操作筆記 find ,count, 大於小於不等, select distinct, groupby,索引


本博客將列舉一些常用的MongoDB操作,方便平時使用時快速查詢,如find, count, 大於小於不等, select distinct, groupby等

1. 大於,小於,大於或等於,小於或等於,不等於

  • $gt: 大於
  • $lt: 小於
  • $gte: 大於或等於
  • $lte: 小於或等於
  • $ne: 不等於
// greater than : field > value
db.collection.find({ "field" : { $gt: value } } ); 

// less than : field < value
db.collection.find({ "field" : { $lt: value } } ); 

// greater than or equal to : field >= value
db.collection.find({ "field" : { $gte: value } } ); 

// less than or equal to : field <= value
db.collection.find({ "field" : { $lte: value } } ); 

// not equal: field != value
db.collection.find( { "field" : { $ne : value } } );

也可以合併在一條語句內:

// value1 < field < value
db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); 

2. value是否在List中:in 和 not in

db.collection.find( { "field" : { $in : array } } );
db.things.find({j:{$in: [2,4,6]}});
db.things.find({j:{$nin: [2,4,6]}});

3. 判斷元素是否存在 $exists

$exists用來判斷一個元素(field)是否存在:

db.things.find( { a : { $exists : true } } ); 
db.things.find( { a : { $exists : false } } ); 

4. select distinct的實現:

  • 鍵值去重 類似於mysql中的 select distinct userId from consumerecords

    db.consumerecords.distinct("userId"):
    
  • 過濾之後去重, 類似於mysql中的select distinct userId from consumerecords where act="charge"

    db.consumerecords.distinct("userId",{act:"charge"}):
    
  • 去重之後求記錄數, 類似於mysql中的 select count(distinct userId) from consumerecords

    db.consumerecords.distinct("userId").length:
    

5. 查詢嵌入對象的值

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

注意用法是author.name

db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})

如果我們要查詢 authors name 是Jane的, 我們可以這樣:

db.blog.findOne({"author.name" : "Jane"})

如果不用點,那就需要用下面這句才能匹配:

db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})

6. 數組大小匹配 $size

$size是匹配數組內的元素數量的,如有一個對象:{a:[“foo”]},他只有一個元素:

下面的語句就可以匹配:

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

7. 全部匹配 $all

allall和in類似,但是他需要匹配條件內所有的值:

如有一個對象:

{ a: [ 1, 2, 3 ] }
下面這個條件是可以匹配的:

db.things.find( { a: { $all: [ 2, 3 ] } } );
但是下面這個條件就不行了:

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

8. 正則表達式

mongo支持正則表達式,如:

// 後面的i的意思是區分大小寫
db.customers.find( { name : /acme.*corp/i } ); 

9. group的實現

  • 分組求和:類似於mysql中的select act,sum(count) from consumerecords group by act

    db.consumerecords.group(
        {
        key:{act:true}, 
        initial:{ct:0},    
        $reduce:function(doc,prev)  
            {
            prev.ct = prev.ct + doc.count    
            }
        }
    )
    
    
  • 分組求和,過濾,類似mysql中的select act,sum(count) from consumerecords group by act having act="charge"

    db.consumerecords.group(
    {
        key:{act:true}, 
        initial:{ct:0},    
        $reduce:function(doc,prev)  
            {
            prev.ct = prev.ct + doc.count    
            },
        condition:{act:"charge"}
    }
    )
    

10. forEach

舉例:可以用於複製collection

db.test(複製源表).find().forEach(function(x){
    db.target(目的表).insert(x);
})

11. 索引

單字段索引 (Single Field Index)

    db.person.createIndex( {age: 1} ) 

上述語句針對age創建了單字段索引,其能加速對age字段的各種查詢請求,是最常見的索引形式,MongoDB默認創建的id索引也是這種類型。

{age: 1} 代表升序索引,也可以通過{age: -1}來指定降序索引,對於單字段索引,升序/降序效果是一樣的。

複合索引 (Compound Index)

複合索引是Single Field Index的升級版本,它針對多個字段聯合創建索引,先按第一個字段排序,第一個字段相同的文檔按第二個字段排序,依次類推,如下針對age, name這2個字段創建一個複合索引。

    db.person.createIndex( {age: 1, name: 1} ) 

多key索引 (Multikey Index)

當索引的字段爲數組時,創建出的索引稱爲多key索引,多key索引會爲數組的每個元素建立一條索引,比如person表加入一個habbit字段(數組)用於描述興趣愛好,需要查詢有相同興趣愛好的人就可以利用habbit字段的多key索引。

{"name" : "jack", "age" : 19, habbit: ["football, runnning"]}
db.person.createIndex( {habbit: 1} )  // 自動創建多key索引
db.person.find( {habbit: "football"} )

查詢索引

mongo-9552:PRIMARY> db.person.getIndexes() // 查詢集合的索引信息
[
    {
        "ns" : "test.person",  // 集合名
        "v" : 1,               // 索引版本
        "key" : {              // 索引的字段及排序方向
            "_id" : 1           // 根據_id字段升序索引
        },
        "name" : "_id_"        // 索引的名稱
    }
]

Ref

  1. momgo agg 操作http://www.runoob.com/mongodb/mongodb-aggregate.html
  2. https://www.cnblogs.com/zhouxuchen/p/5136446.html
  3. https://docs.mongodb.com/manual/aggregation/
  4. https://yq.aliyun.com/articles/33726
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章