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

e0bqpujr  于 2022-12-03  发布在  Go
关注(0)|答案(1)|浏览(90)

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

[
  {
    _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.是否可以直接从查询中获得预期结果?
1.我的查询哪里出错了?
1.我应该阅读哪些材料来涵盖与此查询相关的更多高级概念?
任何帮助都将不胜感激。如果这个问题太简单,我很抱歉。

omtl5h9j

omtl5h9j1#

一个选项是合并查询尝试以:
1.获取包含cured项的所有文档:假的

  1. $filterhistory数组以仅包含此类项目
db.collection.aggregate([
  {$match: {
      history: {$elemMatch: {cured: false}}
  }},
  {$set: {
      history: {
        $filter: {
          input: "$history",
          cond: {$eq: ["$$this.cured", false]}
        }
      }
  }}
])

了解它在playground example上的工作原理

相关问题