【问题标题】:How to get Mongo data using aggregate MongoDB version 3.0如何使用聚合 MongoDB 3.0 版获取 Mongo 数据
【发布时间】:2023-03-20 13:15:02
【问题描述】:

假设我们有 10 个集合,那么我们必须根据 tag_id 找到计数。例如,如果tag_id包含0和1,那么我们必须统计所有数据,以及统计没有tag_id的数据,或者tag_id为null的数据。然后如果它有 unread : false 那么输出来,所有未读的计数。

查找 tag_id 的计数和 false 时的未读计数。

{
        "_id": ObjectId("5912c7240520df77f0c2c18a"),
        "email_id": "54",
        "unread": "false",
        "__v": NumberLong(0),
        "tag_id": ["0"

        ]
    }, {
        "_id": ObjectId("5912c71e0520df77f0c2c189"),
        "email_id": "55",
        "unread": "false",
        "__v": NumberLong(0),
        "tag_id": [
            "1"
        ]
    }, {
        "_id": ObjectId("5912c71d0520df77f0c2c186"),
        "email_id": "51",
        "unread": "false",
        "__v": NumberLong(0),
        "tag_id": [
            "2", "1"
        ]
    }

预期结果:

{
    "data": [{
        "tag_id": "1",
        "count_email": 1,(count of email on the basis of tag_id)
        "unread": 9(count the unread on the basis of output of tag_id)
    }, {
        "tag_id": "3",
        "count_email": 45,
        "unread": 3
    }, {
        "tag_id": "2",
        "count_email": 5,
        "unread": 4
    }, {
        "id": null,
        "count_email": 52,
        "unread": 35
    }]
}

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    试试下面的代码 参考-https://docs.mongodb.com/manual/reference/operator/aggregation/eq/

    https://docs.mongodb.com/manual/reference/operator/aggregation/cond/

    https://docs.mongodb.com/manual/reference/operator/aggregation/group/

    DB.aggregate([
                    {$project:
                    {
                        tag_id: '$tag_id',
                        unreadcount: { $cond: [ { $eq: [ '$unread', 'true' ] }, 1, 0 ] }
                    }},
                    { $group: {
                        _id: '$tag_id',
                        unread: { $sum: '$unreadcount'},
                    }}
                ], function (err, results) {
                    console.log(results);
                })
    

    【讨论】:

    • 它给了我错误 Unexpected token, expected , (70:24) 68 | 69 | req.email.aggregate([ > 70 | $project: 你能修复这个错误以便我可以使用它
    • 我以为您是从 DB 获取这些集合的。什么是 req.email?你能粘贴整个错误信息吗?
    • 它是一个语法错误 SyntaxError: /var/www/html/hr_system/src/controllers/fetch_email.js: Unexpected token, expected , (70:24) 68 | 69 | req.email.aggregate([ > 70 | $project: | ^ 71 | { 72 | tag_id: '$tag_id', 73 | unreadcount: { $cond: [ { $eq: [ '$unread', 'true' ] }, 1, 0 ] }
    • DB.aggregate([ {$project: { tag_id: '$tag_id', unreadcount: { $cond: [ { $eq: [ '$unread', 'true' ] }, 1, 0 ] } }} { $group: { _id: '$tag_id', 未读: { $sum: '$unreadcount'}, }} ], function (err, results) { console.log(results); })
    • 项目前观察花括号,我错过了。
    猜你喜欢
    • 2017-10-10
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2013-12-19
    相关资源
    最近更新 更多