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

时间:2017-05-11 11:42:29

标签: javascript angularjs node.js mongodb mongoose

假设我们有10个集合,那么我们必须在tag_id的基础上找到计数。例如,如果tag_id包含0和1,那么我们必须计算所有数据,以及计算没有tag_idtag_id为空的数据。然后如果它有未读:false则输出到来,计算所有未读。

在false时查找tag_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
    }]
}

1 个答案:

答案 0 :(得分:1)

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

以下查询将$unwind tag_id后跟$group来计算email$cond运算符以计算unread电子邮件。

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