1

I am using below aggregate query to get the count of fields from my collection.

Worksheet.aggregate([
 {
   "$group": {
        "_id": null,
        "todayBilling": {
          "$sum": {
            "$cond": [{ "$and" : [ {"$eq": [ "$isBilling", true]}, {$eq: [ "$date",new Date(moment().format('l'))] } ]},"$hours",0] 
          }
        },
        "todayProjects":{
          "$sum": {
            "$cond":  [{ $eq: [ "$date",new Date(moment().format('l'))] },1,0] 
          }
        }
    }
 }
])

Below is my worksheet collection:

/* 1 */
{
    "_id" : ObjectId("5c34d84926471a1ce0d3103c"),
    "isBilling" : true,
    "isActive" : true,
    "reportSent" : false,
    "projectId" : ObjectId("5c34d81d26471a1ce0d3103b"),
    "hours" : 6,
    "date" : ISODate("2019-01-07T12:00:00.000-06:30"),
}

/* 2 */
{
    "_id" : ObjectId("5c34d8d226471a1ce0d3103e"),
    "isBilling" : true,
    "isActive" : false,
    "reportSent" : false,
    "projectId" : ObjectId("5c34d81d26471a1ce0d3103b"),
    "hours" : 3,
    "date" : ISODate("2019-01-07T12:00:00.000-06:30"),
}

Now, I have same projectId in both documents, and todayProjects is giving me 2, But i don't want to sum if project id is same as previous.

Below is the output which i want:

{
 todayBilling: 6(it is calculating current date vise)
 todayProjects: 3(it should be calculate current date vise)
}
Rajat
  • 486
  • 1
  • 10
  • 35
  • Possible duplicate of [Conditional $sum in MongoDB](https://stackoverflow.com/questions/14102596/conditional-sum-in-mongodb) – nem035 Jan 08 '19 at 17:50
  • @nem035, How can you say that, it is duplicate. Your refrence didn't solved my issue anymore. – Rajat Jan 08 '19 at 17:55

0 Answers0