如何使用聚合MongoDB获取数据Mongo数据 [英] How to get data Mongo data using aggregate MongoDB
问题描述
假设我们有10个集合,那么我们必须在tag_id
的基础上找到计数.例如,如果tag_id
包含0和1,则我们必须对所有数据进行计数,并对不具有tag_id
或tag_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屋!