mongo之聚合

表結構:

{
    "_id" : NumberLong(4306182),
    "id" : "xxxxx",
    "user_id" : "xxxxx",
    "entry_date" : ISODate("2015-10-30T14:59:57.000+08:00"),
    "goods_id" : xxx,
    "goods_verno" : xx,
    "goods_name" : "測試商品",
    "powers" : [ 
        {
            "end_date" : ISODate("2015-11-25T00:00:00.000+08:00"),
            "days" : 30,
            "product_id" : 245,
            "max_child_count" : 4,
            "is_parent_manager" : 1,
            "product_name" : "測試產品",
            "funs" : [ 
                785, 
                820, 
                821, 
                822, 
                823, 
                824, 
                825, 
                826, 
                827, 
                828, 
                829, 
                830, 
                831, 
                832, 
                833, 
                834, 
                835, 
                836
            ],
            "code" : "201503",
            "start_date" : ISODate("2015-10-30T00:00:00.000+08:00"),
            "max_pdu_count" : 8
        }
    ]
}


查詢方式:

db.function_power_data.aggregate(

{
    "$match":{"user_id":"109095","powers":{"$ne":[]}}//查詢條件
},
{
    "$project":{"_id":0,"entry_date":1,"goods_id":1,"powers":1}//顯示字段
},
{
    "$unwind":"$powers"//拆分數組
},
{
    "$group":{"_id":"$goods_id","entry_date":{"$max":"$entry_date"},"end_date":{"$max":"$powers.end_date"}}//分組統計
},
{
    "$sort":{"_id":1}   //排序
},
{
    "$skip":1//跳過前幾條數據
},
{
    "$limit":2//顯示記錄數
}

);


統計函數:

表達式 描述 實例
$sum 計算總和。 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])
$avg 計算平均值 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])
$min 獲取集合中所有文檔對應值得最小值。 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}])
$max 獲取集合中所有文檔對應值得最大值。 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}])
$push 在結果文檔中插入值到一個數組中。 db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])
$addToSet 在結果文檔中插入值到一個數組中,但不創建副本。 db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}])
$first 根據資源文檔的排序獲取第一個文檔數據。 db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}])
$last 根據資源文檔的排序獲取最後一個文檔數據 db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])

聚合框架中管道概念常用的幾個操作:

  • $project:修改輸入文檔的結構。可以用來重命名、增加或刪除域,也可以用於創建計算結果以及嵌套文檔。
  • $match:用於過濾數據,只輸出符合條件的文檔。$match使用MongoDB的標準查詢操作。
  • $limit:用來限制MongoDB聚合管道返回的文檔數。
  • $skip:在聚合管道中跳過指定數量的文檔,並返回餘下的文檔。
  • $unwind:將文檔中的某一個數組類型字段拆分成多條,每條包含數組中的一個值。
  • $group:將集合中的文檔分組,可用於統計結果。
  • $sort:將輸入文檔排序後輸出。
  • $geoNear:輸出接近某一地理位置的有序文檔。


發佈了25 篇原創文章 · 獲贊 8 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章