【问题标题】:MongoDB find among subdocumentsMongoDB 在子文档中查找
【发布时间】:2021-07-25 05:55:54
【问题描述】:

我有一堆文档,每个文档都是这样格式化的:

{
  "faculty": "Some Faculty",
  "students": [
      {
        "id": "51230867123",
        "age": "21",
        "name": "awdawdawdawawd"
      },
      {
        "id": "0217356102",
        "age": "22",
        "name": "awdawd"
      },
      ...
      ]
}

我已经使用 insertMany([...]) 将这些文档插入到单个 MongoDB 集合中,所以现在我的 students 表如下所示:

{
  "faculty": "Some Faculty",
  "students": [
      {
        "id": "51230867123",
        "age": "21",
        "name": "John Doe"
      },
      {
        "id": "0217356102",
        "age": "22",
        "name": "Jane Doe"
      },
      ...
      ]
},
{
  "faculty": "Other Faculty",
  "students": [
      {
        "id": "1240876124",
        "age": "21",
        "name": "Jimmy Doe"
      },
      {
        "id": "2309857120578",
        "age": "22",
        "name": "Johnny Doe"
      },
      ...
      ]
},
...

我非常想知道如何对某些子文档执行find 查询,特别是students。例如,我想find all students.namestudents.age > 23。我尝试了很多查询,包括db.students.find({"students.age": {$gt: /.*B.*/}}, {_id: 0, "students.name": 1}),但这样的查询总是返回至少一个学生满足条件的整个文档。我想查询个别学生。这可以使用find(没有aggregate)吗?

使用aggregate,可以使用unwrap,这正是我需要做的。不过,我希望有一些技巧可以与 find 一起使用来实现这种行为。

【问题讨论】:

    标签: mongodb subdocument


    【解决方案1】:

    您可以在 find 和 findOne 方法的投影中使用聚合运算符,从 MongoDB 4.2 开始,

    • $filter 迭代学生数组的循环并检查所需条件,它将返回过滤结果
    • $map 迭代上述过滤结果的循环并仅返回 name
    db.collection.find(
      { "students.age": { $gt: "23" } },
      {
        "students": {
          $map: {
            input: {
              $filter: {
                input: "$students",
                cond: { $gt: ["$$this.age", "23"] }
              }
            },
            in: "$$this.name"
          }
        }
      }
    )
    

    Playground

    【讨论】:

    • 有点好奇,虽然您指定了两次条件。这种方法需要这样做吗?
    • 是的,它需要,查询部分过滤主根文档,投影过滤器匹配学生数组中的对象。
    猜你喜欢
    • 2016-08-25
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多