如何在MongoDB中执行高级子文档查询?

问题描述

我有一个架构(案例),其中包含一个子架构(评估)数组。

我的案例模式如下:

const caseSchema = new mongoose.Schema({
    patient: {
        type: String,default: 'Password can\'t be empty' 
    }
    description: {
        type: String,required: 'Case description can\'t be empty'
    },assessments: [assessmentSchema]
});

我的评估方案如下

const assessmentSchema = new mongoose.Schema({
    doctor: {
        type: String,required: 'Doctor can\'t be empty'
    },doa: Date,slots: String
});

我的问题是在整个馆藏中找到所有评估文件(指定了医生和doa)。但是由于这些详细信息仅在子模式中可用,因此我不知道如何解决此问题。而且我也无法将医生字段添加到“案例模式”中,因为一个案例中可能有很多医生。我在用猫鼬。我在互联网上搜索了很多地方,但无法找到解决方案。请帮助我。

解决方法

我认为您需要这样的东西。

这是一个汇总,其中$project阶段用于传递带有请求字段的文档。 传递到下一阶段的字段是与过滤器匹配的字段。 在过滤器中,我们使用$eq条件来检查“ doctor”和“ slots”字段。

请注意,您必须使用$运算符,即位置运算符。

db.collection.aggregate([
  {
    "$project": {
      "_id": 0,"assessments": {
        "$filter": {
          "input": "$assessments","as": "ass","cond": {
            "$eq": [
              "$$ass.doctor","doctor1"
            ],"$eq": [
              "$$ass.slots","slots1"
            ]
          }
        }
      }
    }
  }
])

这里是一个游乐场example

编辑:通过此新查询,您可以获取所需的所有字段。

db.collection.aggregate([
  {
    "$project": {
      "patient": 1,"description": 1,"as": "as","cond": {
            "$eq": [
              "$$as.doctor","$eq": [
              "$$as.slots","slots1"
            ]
          }
        }
      }
    }
  }
])

注意只有一点点区别。 在$project中,您可以决定要显示/重置/ ... reference $project

因此,在查询字段中添加caseSchema即可。