内部数组的MongoDb查询

时间:2017-12-12 03:52:00

标签: mongodb

我有以下文档结构

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

我需要一个查询来查找此人从此系列中离开的总天数。只有当状态为已批准且休假类型为“离开”时,才会考虑休假天数。 mongodb中有没有办法查询并查找数字?

1 个答案:

答案 0 :(得分:1)

尝试以下

Users.aggregate([
{
    $match:{
        _id:user_id,
        "leaveHistory.type ":"Leave",
        "leaveHistory.status": "Approved"
    }
}, 
{
    unwind:"leaveHistory"
}, 
{
    $project:{
         $count: "numberofDays"
    }   
}
], (err, results)=>{
    console.log(err, results);
})