【问题标题】:Mongoose Find all Documents by subdocument and filter out subdocs that dont matchMongoose 按子文档查找所有文档并过滤掉不匹配的子文档
【发布时间】:2023-03-20 02:15:01
【问题描述】:

我正在尝试查询集合中包含特定用户数据的所有文档而不返回所有子文档(有大量子文档)

示例文档

[
    {
        "id": 1,
        "title": "Document 1",
        "users": [
            { "id": "a", "name": "User 1" },
            { "id": "b", "name": "User 1" },
        ]
    },
    {
        "id": 2,
        "title": "Document 2",
        "users": [
            { "id": "b", "name": "User 1" },
        ]
    },
    {
        "id": 3,
        "title": "Document 3",
        "users": [
            { "id": "a", "name": "User 1" },
            { "id": "b", "name": "User 1" },
            { "id": "c", "name": "User 1" },
        ]
    }
]

这里我们有 3 个文档,其中 2 个使用了 id A,来查询我正在做的用户 A 存在的所有文档:

collection.findManyByQuery({
    users: {
        $elemMatch: {
            id: 'a'
        }
    }
})

这会返回正确的 id 为 1 和 3 的文档。但是我试图返回用户数组中只有用户 A 对象的文档,所以我的结果看起来像这样

[
    {
        "id": 1,
        "title": "Document 1",
        "users": [
            { "id": "a", "name": "User 1" },
        ]
    },
    {
        "id": 3,
        "title": "Document 3",
        "users": [
            { "id": "a", "name": "User 1" },
        ]
    }
]

我尝试了$unwind: 'users' 和几个过滤器,但没有得到想要的结果。

【问题讨论】:

    标签: mongodb mongoose subdocument


    【解决方案1】:

    使用projection 舞台。

    根据文档:

    投影参数决定了匹配文档中返回哪些字段

    因此,使用users.$: 1 您是在告诉 mongo:“返回符合条件的用户的值”。在这种情况下,条件是id: "a"

    db.collection.find({
      users: {
        $elemMatch: {
          id: "a"
        }
      }
    },
    {
      "users.$": 1
    })
    

    例如here

    您也可以使用users.id 来查找查询,例如this example

    也许是一个更干净的查询,只有两行:

    db.collection.find({
      "users.id": "a"
    },
    {
      "users.$": 1
    })
    

    编辑:

    要向输出添加更多值(例如 titleid),您必须添加到投影阶段。默认情况下,投影只返回_id1true 的值。

    查看this example

    【讨论】:

    • 太好了,这很有帮助!但是现在它只返回匹配的子文档,而不是父文档中的其余信息。有没有办法像您的解决方案一样返回文档+子文档?
    • 是的,在投影中添加要返回的字段。检查this example
    猜你喜欢
    • 2015-07-18
    • 2020-12-29
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 2020-07-16
    • 2017-02-28
    相关资源
    最近更新 更多