如果嵌入式文档数组中的每个文档都符合条件,则获取文档

时间:2018-08-06 11:02:20

标签: arrays mongodb mongodb-query

我具有以下文档结构:

[
  {
    "_id": "5b67f78681b1ac90a0106355",
    "nrc": "22652"
    "schedules": [
      {
        "time_ini": "1600",
        "time_fin": "1850",
        "classroom": ".NOREQ",
        "L": null,
        "M": "M",
        "I": null,
        "J": null,
        "V": null,
        "S": null,
        "D": null,
        "date_ini": "06-AUG-18",
        "date_fin": "24-NOV-18"
      },
      {
        "time_ini": "1900",
        "time_fin": "2150",
        "classroom": ".NOREQ",
        "L": null,
        "M": "M",
        "I": null,
        "J": null,
        "V": null,
        "S": null,
        "D": null,
        "date_ini": "06-AUG-18",
        "date_fin": "24-NOV-18"
      }
    ]
  },
  {
    "_id": "5b67f79b81b1ac90a0106f0b",
    "nrc": "11567",
    "schedules": [
      {
        "time_ini": "0930",
        "time_fin": "1120",
        "classroom": ".ML_608",
        "L": null,
        "M": "M",
        "I": null,
        "J": null,
        "V": null,
        "S": null,
        "D": null,
        "date_ini": "03-JUL-18",
        "date_fin": "24-NOV-18"
      },
      {
        "time_ini": "1400",
        "time_fin": "1550",
        "classroom": ".ML_608",
        "L": null,
        "M": null,
        "I": null,
        "J": null,
        "V": "V",
        "S": null,
        "D": null,
        "date_ini": "03-JUL-18",
        "date_fin": "24-NOV-18"
      },
      {
        "time_ini": "1000",
        "time_fin": "1150",
        "classroom": ".NOREQ",
        "L": null,
        "M": null,
        "I": null,
        "J": null,
        "V": null,
        "S": "S",
        "D": null,
        "date_ini": "03-JUL-18",
        "date_fin": "24-NOV-18"
      }
    ]
  }
]

我想在日程安排中找到与特定日期匹配的所有文档。例如,我想获取M数组中每个元素仅具有schedules属性值的文档,所以我尝试了:

db.classes.find({
    "schedules": {
        "$elemMatch": {
            "L": null,
            "I": null,
            "J": null,
            "V": null,
            "S": null
        }
    }
})

但是通过此查询,我将获得两个文档,因为第二个文档在数组上至少具有一个与条件匹配的元素。但是我只想得到第一个。

基本上,我正在寻找$elemMatch来获取包含schedules数组且其所有元素均符合条件的文档。

谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用以下查询来获取文档,其中包含所有元素,其中M具有值。

db.classes.find({
  schedules: {
    $all: [{
      $elemMatch: {
        M: {$ne: null},
        L: null,
        I: null,
        J: null,
        V: null,
        S: null,
        D: null
      }
    }]
  }
})

答案 1 :(得分:0)

我使用$nor找到了答案:

db.classes.find({
    "schedules.M": "M",
    "$nor" : [
        {
            "schedules.L": "L"
        },
        {
            "schedules.I": "I"
        },
        {
            "schedules.J": "J"
        },
        {
            "schedules.V": "V"
        },
        {
            "schedules.S": "S"
        }
    ]
})

$nor数组中,我将要排除的所有天都放在我要包括的所有天之外。