如何根据 MongoDB 中的条件从数组中获取元素?

How to get elements from an array based on condition in MongoDB?

我是 MongoDB 的初学者,下面是我的示例文档:

{
"plan_id" : "100",
"schedule_plan_list" : [ 
    {
        "date" : "01-05-2020",
        "time" : "9:00AM -10:00AM"
    }, 
    {
        "date" : "02-05-2020",
        "time" : "10:00AM -11:00AM"
    }, 
    {
        "date" : "03-05-2020",
        "time" : "9:00AM -10:00AM"
    }, 
    {
        "date" : "04-05-2020",
        "time" : "9:30AM -10:30AM"
    }, 
    {
        "date" : "05-05-2020",
        "time" : "9:00AM -10:00AM"
    }, 
    {
        "date" : "06-05-2020",
        "time" : "9:00AM -10:00AM"
    }, 
    {
        "date" : "07-05-2020",
        "time" : "9:30AM -10:30AM"
    }, 
    {
        "date" : "08-05-2020",
        "time" : "4:00PM -5:00PM"
    }
  ]
}  

我想获取接下来的 5 个元素 ** 基于给定的日期是 **“02-05-2020”

我给定的查询提取仅匹配“02-05-2020”,但我想要 “02-05-2020”,“03-05-2020”,..06-05-2020 "

 db.getCollection('schedule_plans').find({"plan_id" : "100"},{_id:0,"schedule_plan_list": { "$elemMatch": { "date" : "02-05-2020"}}})

所以有人帮我解决这个问题

您可以尝试以下聚合查询:

db.collection.aggregate([
{ $match: { "plan_id": "100" } },
/** You can re-create `schedule_plan_list` field with condition applied & slice the new array to keep required no.of elements in array */
{
  $project: {
    _id: 0,
    "schedule_plan_list": {
      $slice: [
        {
          $filter: { input: "$schedule_plan_list", cond: { $gte: [ "$$this.date", "02-05-2020" ] } }
        },
        5
      ]
    }
  }
})

测试:mongoplayground

参考: aggregation