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

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

问题描述

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

Suppose we have 10 collection, 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
    }]
}

推荐答案

您可以使用以下聚合管道.

You can use below aggregation pipeline.

以下查询将对$unwind tag_id$group进行计数,对email进行计数,对$cond运算符进行计数,对unread电子邮件进行计数.

The below query will $unwind the tag_id followed by $group to count email and $cond operator to count the unread email.

db.collection.aggregate(
 {$unwind:{path:"$tag_id", preserveNullAndEmptyArrays:true}}, 
 {$group:{
    _id:"$tag_id", 
     count_email:{$sum:1},
     unread:{$sum:{$cond:[{$eq:["$unread", "false"]}, 0, 1]}}
    }
  }
);

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

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