繁体   English   中英

如何从 MongoDB 中的嵌套文档中过滤并获取所需数据?

[英]How to filter and get required data from a nested document in MongoDB?

我的数据库中有这个结构。

[
  {
    _id: ObjectId("6386ef039775398be3620c76"),
    firstName: 'A',
    lastName: 'BA',
    age: 34,
    history: [
      { disease: 'fever', cured: true },
      { disease: 'malaria', cured: false }
    ]
  },
  {
    _id: ObjectId("6386ef239775398be3620c77"),
    firstName: 'AA',
    lastName: 'BA',
    age: 24,
    history: [
      { disease: 'cold', cured: true },
      { disease: 'thyroid', cured: false }
    ]
  }
]

我想要实现的是一个查询,它会给我这样的数据:

询问

 db.collection.find({$filter:{history:{$elemMatch:{cured:false}}}

预期结果:

[
  {
    _id: ObjectId("6386ef039775398be3620c76"),
    firstName: 'A',
    lastName: 'BA',
    age: 34,
    history: [
      { disease: 'malaria', cured: false }
    ]
  },
  {
    _id: ObjectId("6386ef239775398be3620c77"),
    firstName: 'AA',
    lastName: 'BA',
    age: 24,
    history: [
      { disease: 'thyroid', cured: false }
    ]
  }
]

我试过的是

1.

db.collection.find({$filter:{history:{$elemMatch:{cured:false}}}
  db.collection.aggregate([
    {
      $project: {
        history: {
          $filter: { 
           input: "$history",
            as: "items",
            cond: { cured: false } 
          },
        },
      },
    },
  ]);
db.collection.find({history:{$elemMatch:{cured:true}}},{'history.cured':1})

但是这些查询都没有给出预期的结果,

疑问/问题:

  1. 是否可以直接从查询中获得预期结果?
  2. 我的查询哪里出错了?
  3. 我 go 应该通过什么材料来涵盖与此查询相关的更多高级概念?

任何帮助将非常感激。 如果这个问题太基础了,我深表歉意。

一种选择是将您的查询尝试合并到:

  1. 获取所有包含cured : false 项的文档
  2. $filter history数组只包含这些项目
db.collection.aggregate([
  {$match: {
      history: {$elemMatch: {cured: false}}
  }},
  {$set: {
      history: {
        $filter: {
          input: "$history",
          cond: {$eq: ["$$this.cured", false]}
        }
      }
  }}
])

playground 示例中查看它是如何工作的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM