MongoDB 聚合查詢 $unwind

在aggregate中,經常會遇到一些字段屬性是數組對象,而後又須要對這些數組對象進行統計。
這時候就須要用到$unwind操做符。這是一個經常使用的,又容易被忽略的一個操做。數組

定義

  • field 版spa

    { $unwind: <field path> } 
  • document版code

    {
      $unwind:
        {
          path: <field path>, includeArrayIndex: <string>, preserveNullAndEmptyArrays: <boolean> } } 
  1. 你要打散的字段
  2. includeArrayIndex,分配一個存該數組索引的字段
  3. preserveNullAndEmptyArrays,是否輸出空內容。

一、插入數據

MongoDB Enterprise > db.mytestcol.insert({user_id:"A_id",bonus:[{ type:"a" ,amount:1000 },{ type:"b" ,amount:2000 },{ type:"b" ,amount:3000 }]}xml

MongoDB Enterprise > db.mytestcol.insert({user_id:"B_id",bonus:[{ type:"a" ,amount:1000 },{ type:"b" ,amount:2000 },{ type:"b" ,amount:3000 }]})對象

二、查看數據

1)普通查看

MongoDB Enterprise > db.mytestcol.find().pretty()
{
        "_id" : ObjectId("5e1d66b240741afd9cfdee9d"),
        "user_id" : "B_id",
        "bonus" : [
                {
                        "type" : "a",
                        "amount" : 1000
                },
                {
                        "type" : "b",
                        "amount" : 2000
                },
                {
                        "type" : "b",
                        "amount" : 3000
                }
        ]
}
{
        "_id" : ObjectId("5e1d66d540741afd9cfdee9e"),
        "user_id" : "A_id",
        "bonus" : [
                {
                        "type" : "a",
                        "amount" : 1000
                },
                {
                        "type" : "b",
                        "amount" : 2000
                },
                {
                        "type" : "b",
                        "amount" : 3000
                }
        ]
}索引

2)$unwind查看,將數組拆開

MongoDB Enterprise > db.mytestcol.aggregate([{"$unwind":"$bonus"}])
{ "_id" : ObjectId("5e1d66b240741afd9cfdee9d"), "user_id" : "B_id", "bonus" : { "type" : "a", "amount" : 1000 } }
{ "_id" : ObjectId("5e1d66b240741afd9cfdee9d"), "user_id" : "B_id", "bonus" : { "type" : "b", "amount" : 2000 } }
{ "_id" : ObjectId("5e1d66b240741afd9cfdee9d"), "user_id" : "B_id", "bonus" : { "type" : "b", "amount" : 3000 } }
{ "_id" : ObjectId("5e1d66d540741afd9cfdee9e"), "user_id" : "A_id", "bonus" : { "type" : "a", "amount" : 1000 } }
{ "_id" : ObjectId("5e1d66d540741afd9cfdee9e"), "user_id" : "A_id", "bonus" : { "type" : "b", "amount" : 2000 } }
{ "_id" : ObjectId("5e1d66d540741afd9cfdee9e"), "user_id" : "A_id", "bonus" : { "type" : "b", "amount" : 3000 } }string

 

3.查詢數據:查詢不一樣user_id下,數據元素type爲b的amount之和與交易筆數

MongoDB Enterprise > db.mytestcol.aggregate([{"$unwind":"$bonus"},{$match:{"bonus.type":"b"}},{$group:{"_id":"$user_id","amount":{$sum:"$bonus.amount"}}}])
{ "_id" : "B_id", "amount" : 5000 }
{ "_id" : "A_id", "amount" : 5000 }class

MongoDB Enterprise > db.mytestcol.aggregate([{"$unwind":"$bonus"},{$match:{"bonus.type":"b"}},{$group:{"_id":"$user_id","amount":{$sum:1}}}])
{ "_id" : "B_id", "amount" : 2 }
{ "_id" : "A_id", "amount" : 2 }test

相關文章
相關標籤/搜索