如何使用聚合MongoDB版本3.0获取Mongo数据

假设我们有10个集合,那么我们必须在tag_id的基础上find计数。 例如,如果tag_id包含0和1,那么我们必须对所有数据进行计数,以及对没有tag_id或tag_id为空的数据进行计数。 那么如果它有未读:false,那么输出来了,所有未读的计数。

findtag_id的计数和错误时的未读计数。

{ "_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/

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

你可以在3.0版本上使用下面的map reducefunction。

 // group by tag_id var map = function() { if(!this.hasOwnProperty('tag_id')) { // include non existing tag_ids emit(null, {count_email: 1,unread: this.unread === "true" ? 1 : 0}); }else { // unwind and emit a unread/email key value pair for each tag entry in array this.tag_id.forEach(function(value) { var key = value; emit(key, {count_email: 1,unread: this.unread === "true" ? 1 : 0}); } } }; // sum unread and email count var reduce = function(key, values) { val = { count_email: 0, unread: 0 }; values.forEach(function(value) { val.count_email += value.count_email; val.unread += value.unread; }) return val; }; db.collection.mapReduce( map, reduce, { out: { "inline" : 1} } ) 

更多https://docs.mongodb.com/manual/tutorial/map-reduce-examples/#calculate-order-and-total-quantity-with-average-quantity-per-item