mongodb与groupby具有多字段计数

时间:2019-06-13 11:29:01

标签: mongodb mongoose mongodb-query aggregation-framework

MongoDB,我有一个像这样的集合

/* 1 */
{
    "_id" : ObjectId("5d02308e129aab55b3df814a"),
    "title" : "fgdfg",
    "user_id" : "5bc5dc03f6d24d29077dd362",
    "click" : false,
    "type_id" : "5d00a304430fee3160ac881f",
    "type" : "user_notification",
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("5d02308e129aab55b3df8149"),
    "title" : "fgdfg",
    "user_id" : "5bc5dc03f6d24d29077dd362",
    "click" : true,
    "type_id" : "5d00a304430fee3160ac881f",
    "type" : "user_notification",
    "__v" : 0
}

/* 3 */
{
    "_id" : ObjectId("5d02308e129aab55b3df8148"),
    "title" : "fgdfg",
    "user_id" : "5bc5dc03f6d24d29077dd362",
    "click" : true,
    "type_id" : "5d00a304430fee3160ac881f",
    "type" : "user_notification",
    "__v" : 0
}

我要按查询和“ type_id”分组进行同一查询,我希望对type_id的“是”和“否”字段有多少个点击?

结论:我希望在单个查询中每个type ID的总type_id计数和“ click”字段“ true”总数。

1 个答案:

答案 0 :(得分:1)

您可以使用MongoDB组,

let query = [{
    $group: {
        _id: "$type_id",
        "true": { $sum: { $cond: [{ $eq: ['$click', true] }, 1, 0] } },
        "false": { $sum: { $cond: [{ $eq: ['$click', false] }, 1, 0] } },

    },
}, {
    $addFields: {
        "addition": { $add: ["$true", "$false"] }
    }
}]