如何在mongodb中使用聚合

如何在mongodb中使用聚合,mongodb,aggregate,Mongodb,Aggregate,我在mongodb中有这样的数据 { "_id" : 1, "data" : "ARIN", "status" : "CLOSED", "createdDate" : Date("2020-02-16T17:32:28+07:00") }, { "_id" : 2, "source" : "ARIN", "status" : "NEW", "createdDate" : Date("2020-02-16T17:32:28+07:00

我在mongodb中有这样的数据

{
    "_id" : 1,
    "data" : "ARIN",
    "status" : "CLOSED",
    "createdDate" : Date("2020-02-16T17:32:28+07:00")
},
{
    "_id" : 2,
    "source" : "ARIN",
    "status" : "NEW",
    "createdDate" : Date("2020-02-16T17:32:28+07:00")
},
{
    "_id" : 3,
    "data" : "APNIC",
    "status" : "ONPROGRESS",
    "createdDate" : Date("2020-02-17T17:32:28+07:00")
},
{
    "_id" : 4,
    "data" : "RIPE",
    "status" : "NEW",
    "createdDate" : Date("2020-02-17T17:32:28+07:00")
}
我想要这样的结果

{
   statusNew : 2,
   statusOnProgress : 1,
   statusClosed : 1
   statusTicketClosedDate1602 : 1,
   statusTicketNewdDate1602 : 1,
   statusTicketOnProgressDate1602 : 0
}

我尝试在mongodb中使用group和cond,但没有效果。如何编写此查询?

您可以使用此查询



使用
$lookup
遍历所有记录,并使用
$facet
为结果中的每个字段生成结果。最后,使用
$count
根据所需条件对记录进行计数。做一些工作:pDo你的意思是每一个新的/进展的/结束的日期,你想得到一个专门的领域?
db.collection.aggregate([{
$group: {
    _id: null,
    statusNew: { $sum: { $cond: [{ "$eq": ["$status", "NEW"] }, 1, 0] } },
    statusOnProgress: { $sum: { $cond: [{ "$eq": ["$status", "ONPROGRESS"] }, 1, 0] } },
    statusClosed: { $sum: { $cond: [{ "$eq": ["$status", "CLOSED"] }, 1, 0] } },
    statusTicketClosedDate1602: {
        $sum: {
            $cond: [{
                $and: [{ "$eq": ["$status", "CLOSED"] },
                { "$gte": ["$createdDate", ISODate("2020-02-16T00:00:00Z")] },
                { "$lt": ["$createdDate", ISODate("2020-02-17T00:00:00Z")] }]
            }, 1, 0]
        }
    },
    statusTicketNewdDate1602: {
        $sum: {
            $cond: [{
                $and: [{ "$eq": ["$status", "NEW"] },
                { "$gte": ["$createdDate", ISODate("2020-02-16T00:00:00Z")] },
                { "$lt": ["$createdDate", ISODate("2020-02-17T00:00:00Z")] }]
            }, 1, 0]
        }
    },
    statusTicketOnProgressDate1602: {
        $sum: {
            $cond: [{
                $and: [{ "$eq": ["$status", "ONPROGRESS"] },
                { "$gte": ["$createdDate", ISODate("2020-02-16T00:00:00Z")] },
                { "$lt": ["$createdDate", ISODate("2020-02-17T00:00:00Z")] }]
            }, 1, 0]
        }
    }
}
}])