0

I have a following document structure

Users:[{
    "name": "test",
    "leaveBalance": 20,
    "leaveHistory": [
       {
          type: "Leave",
          numberofDays:2,
          status:"Approved"
       },
       {
          type: "WFH",
          numberOfDays:1,
          status: "Approved"
       },
       {
           type: "Leave",
           numberOfDays:2,
           status: "Cancelled"
       }
     ]
}, 
{
 ...
}
]

I need a query to find the total number of days a person took leave from this collection. number of days of leave is considered only if status is Approved and leave type is "Leave". Is there a way in mongodb to query and find the number ?

1 Answer 1

1

try below

Users.aggregate([
{
    $match:{
        _id:user_id,
        "leaveHistory.type ":"Leave",
        "leaveHistory.status": "Approved"
    }
}, 
{
    unwind:"leaveHistory"
}, 
{
    $project:{
         $count: "numberofDays"
    }   
}
], (err, results)=>{
    console.log(err, results);
})
Sign up to request clarification or add additional context in comments.

3 Comments

Is this in mongo query syntax ?
yes, mongo have aggregation query framework , that have more methods read more docs.mongodb.com/v3.4/aggregation
The query doesnt seem to work for me. It returns as many values as present in the leaveHistory instead of sum of numberofDays per user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.