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

相关文章
相关标签/搜索