过滤具有日期范围的查找集合

时间:2017-08-29 09:40:01

标签: mongodb mongoose aggregate

如何使用日期范围过滤查找的集合?我尝试了很多方法但却无法获得满意的结果。

以下是我目前的代码

      {
        $lookup: {
          from: "leaves",
          localField: "_leaves",
          foreignField: "_id",
          as: "leaves"
        }
      },
      {
        $project: {
          ....
          leaves: {
            $filter: {
              input: "$leaves",
              as: "leave",
              cond: [
                {
                  $and: [
                    { $gt: ["$$leave.date", start] 
                 },
                    { $lt: ["$$leave.date", end] }
                  ]
                }
              ]
            }
          }

更新1

抱歉不够清楚..

离开集合

    {
            "_id": ObjectId("1"),,
            "_takenBy": ObjectId("..."),
            "date": ISODate("2017-04-19T00:00:00.000Z"),
            ...
    },
    {
            "_id": ObjectId("1"),,
            "_takenBy": ObjectId("..."),
            "date": ISODate("2017-04-30T00:00:00.000Z"),
            ...
    }
    {
            "_id": ObjectId("1"),,
            "_takenBy": ObjectId("..."),
            "date": ISODate("2017-05-01T00:00:00.000Z"),
            ...
    }

    Expected Result:
    {
            "_id": ObjectId("1"),,
            "_takenBy": ObjectId("..."),
            "date": ISODate("2017-04-19T00:00:00.000Z"),
            ...
    },
    {
            "_id": ObjectId("1"),,
            "_takenBy": ObjectId("..."),
            "date": ISODate("2017-04-30T00:00:00.000Z"),
            ...
    }

    So, I have tried to "unwind" and "match" the leaves collection after "lookup"

    {
            $lookup: {
            from: "leaves",
            localField: "_leaves",
            foreignField: "_id",
            as: "leaves"
            }
    },
    { $unwind: "$leaves" },
    {
            $match: {
            "leaves.date": {
            $gt: range.start.toDate(),
            $lt: range.end.toDate()
            }
    }
    },

当我尝试"项目"它,它只返回一个假记录而不是两个, 我确实尝试过" group"但不确定如何将其他集合分组 比如查找后的轮班收集

    {
            $project: {
            user: 1
            leaves: 1
            shifts: 1
    //     }

0 个答案:

没有答案