Mongo query Distinct with Sum is not working

后端 未结 1 978
别跟我提以往
别跟我提以往 2021-01-19 23:09

Here I have updated my question. This is the input data, you can use this command to insert in your local db:

db.pms_teamleadtimesheets.insertMany( [
      {         


        
相关标签:
1条回答
  • 2021-01-19 23:50

    The $group stage has the following prototype form:

    { $group: { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, ... } }
    

    Your field1 is Hours and accumulator1 is sum, Therefore your aggregation should be like this:

    db.pms_teamleadtimesheets.aggregate(
    
      // Pipeline
      [
        // Stage 1
        {
          $match: {
          UserName:"Admin",
          FacilityID:"59a53f0c6077b2a029c52b7f",
          ProjectID:"5a042ba02af18ac8388bd3c0"
          }
        },
    
        // Stage 2
        {
          $group: {
             _id: { ProjectID: "$ProjectID",
                Task: "$Text", Phase: "$phase",
                Comments: "$Comments", 
                TaskType: "$TaskType", 
                Items: "$Items", 
                UserName: "$UserName", 
                IsBillable: "$IsBillable", 
                Date: "$StartDate"
                },
                Hours:{$sum:"$Hours" }
          }
        },
    
        // Stage 3
        {
          $project: {
           _id: 0,
           ProjectID: "$_id.ProjectID", 
           Phase: "$_id.Phase",
           Task: "$_id.Task",
           Comments: "$_id.Comments",
           TaskType: "$_id.TaskType",
           Items: "$_id.Items",
           UserName: "$_id.UserName",
           IsBillable: "$_id.IsBillable",
           Date: "$_id.Date",
           Hours:  { 
             $divide: [ "$Hours", 60 ] 
             } 
          }
        },
    
      ]
    );
    

    Output for with the given test data:

    { 
        "ProjectID" : "5a042ba02af18ac8388bd3c0", 
        "Phase" : "Analysis", 
        "Task" : "Analysis", 
        "Comments" : "2", 
        "TaskType" : "DELIVERY", 
        "Items" : "CRI", 
        "UserName" : "Admin", 
        "IsBillable" : true, 
        "Date" : "29-05-2018", 
        "Hours" : 4.0
    }
    { 
        "ProjectID" : "5a042ba02af18ac8388bd3c0", 
        "Phase" : "Analysis", 
        "Task" : "Analysis", 
        "Comments" : "8", 
        "TaskType" : "DELIVERY", 
        "Items" : "Others", 
        "UserName" : "Admin", 
        "IsBillable" : true, 
        "Date" : "28-05-2018", 
        "Hours" : 4.0
    }
    { 
        "ProjectID" : "5a042ba02af18ac8388bd3c0", 
        "Phase" : "Analysis", 
        "Task" : "Analysis", 
        "Comments" : "4", 
        "TaskType" : "DELIVERY", 
        "Items" : "Others", 
        "UserName" : "Admin", 
        "IsBillable" : true, 
        "Date" : "28-05-2018", 
        "Hours" : 4.0
    }
    

    Further read here

    0 讨论(0)
提交回复
热议问题