如何使用聚合MongoDB 3.0版获取Mongo数据 [英] How to get Mongo data using aggregate MongoDB version 3.0

查看:83
本文介绍了如何使用聚合MongoDB 3.0版获取Mongo数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有10个集合,那么我们必须基于tag_id查找计数.例如,如果tag_id包含0和1,则我们必须对所有数据进行计数,并对不具有tag_id或tag_id为null的数据进行计数.然后,如果它有未读:false,则输出,计算所有未读.

Suppose we have 10 collections, then we have to find the count on the basis of tag_id. For example, if tag_id contains 0 and 1, then we have to count all the data, as well as counting the data that don't have tag_id, or where tag_id is null. Then if it has unread : false then the output comes, count of all the unread.

查找为false时的tag_id计数和未读计数.

Find the counts of tag_id and counts of unread when 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
    }]
}

推荐答案

尝试以下代码 请参阅- https://docs.mongodb.com/manual/reference/operator /aggregation/eq/

Try the following code Refer - https://docs.mongodb.com/manual/reference/operator/aggregation/eq/

https://docs.mongodb.com/manual/reference/运算符/聚合/cond/

https://docs.mongodb.com/manual/reference/运算符/聚合/组/

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);
            })

这篇关于如何使用聚合MongoDB 3.0版获取Mongo数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆