分组复杂的过滤记录

时间:2019-06-14 13:53:11

标签: mongodb

我只想知道我有多少人具有特定的区块ID。在按块ID过滤数组后,我尝试对'bot_survey'进行分组,但无法获得正确的结果。这是我的2条记录

{
    date: '2019-06-13',
    blocks:[
        {
            block_id: '5caf27cfcb4b530e4d51bb72',
            triggered_by:[
                {
                    person_id: '2342'
                },
                {
                    person_id: '436'
                }
            ]
        }
    ]

},
{
    date: '2019-06-14',
    blocks:[
        {
            block_id: '5caf27cfcb4b530e4d51bb72',
            triggered_by:[
                {
                    person_id: '2342'
                },
                {
                    person_id: '965'
                }
            ]
        }
    ]

},

这是我的查询

db.getCollection('analytics').aggregate([
   {$match: {date: {$lte: '2019-06-13'},"blocks.block_id": '5caf27cfcb4b530e4d51bb72'}},
   {
      $project: {
         date: 1,
         bot_survey: {
            $filter: {
               input: "$blocks",
               as: "blocks",
               cond: { $eq: [ "$$blocks.block_id", '5caf27cfcb4b530e4d51bb72' ] }
            }
         }
      }
   },
   {
    $group: {
      _id: {date: "$bot_survey.triggered_by.person_web_id"},
   }
  }
])

但是我需要类似

的结果
{
 person_id: '2342',
 person_id: '436',
 person_id: '965'
}

这样我就可以得到结果计数。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以根据输入数据进行汇总,

db.orders.aggregate([
    {
        $unwind: "$blocks"
    },
        {
        $unwind: "$blocks.triggered_by"
    },
    {
        $group: {
           _id: "$blocks.block_id",
           triggered_by: { $addToSet: 
          {person_id:"$blocks.triggered_by.person_id"}  }
    }
}
])

输出:

{"_id":"5caf27cfcb4b530e4d51bb72","triggered_by":[{"person_id":"2342"},{"person_id":"965"},{"person_id":"436"}]}