【问题标题】:Mongodb - How to Join two documents by key in second document and merge child documents as array to parent documentMongodb - 如何在第二个文档中按键连接两个文档并将子文档作为数组合并到父文档
【发布时间】:2021-08-23 03:54:20
【问题描述】:

我有三个用 mongodb 编写的文档。它主要类似于文件夹和文件结构。我正在尝试通过输入类别 ID 来搜索文件类别。

如果有任何文件与类别 id 匹配,我需要将父文件夹文档中的这些文件作为嵌入数组列出来作为响应。

文档文件夹

[
    {
        _id: "5f7763103a4af84960f86ae6",
        folderName: "abcd"
    },
    {
        _id: "5f7763103a4af84960f86ae7",
        folderName: "qwerty"
    },
    {
        _id: "5f7763103a4af84960f86ae8",
        folderName: "asdfgh"
    },
]

文档文件

[
    {
        _id: "1c7763103a4af84960f86aa5",
        fileName: "test file 1",
        folderId: "5f7763103a4af84960f86ae7",
        categoryId: "6b7763103a4af84960f86ae2"
    },
    {
        _id: "1c7763103a4af84960f86aa6",
        fileName: "test file 2",
        folderId: "5f7763103a4af84960f86ae7",
        categoryId: "6b7763103a4af84960f86ae2"
    },
    {
        _id: "1c7763103a4af84960f86aa7",
        fileName: "test file 3",
        folderId: "5f7763103a4af84960f86ae6",
        categoryId: "6b7763103a4af84960f86ae2"
    },
]

文档类别

[
    {
        _id: "6b7763103a4af84960f86ae1",
        categoryName: "misc"
    },
    {
        _id: "6b7763103a4af84960f86ae2",
        categoryName: "images"
    },
    {
        _id: "6b7763103a4af84960f86ae3",
        categoryName: "other"
    },
]

当我在 files 文档中按 categoryId 搜索时,我需要将所有匹配的文件分组到与父文件夹名称分组的数组中。

我期待如下结果

    {
        folder: {
            _id: "5f7763103a4af84960f86ae7",
            folderName: "qwerty",
            files: [
                {
                    _id: "1c7763103a4af84960f86aa5",
                    fileName: "test file 1",
                    folderId: "5f7763103a4af84960f86ae7",
                    categoryId: "6b7763103a4af84960f86ae2"
                },
                {
                      _id: "1c7763103a4af84960f86aa6",
                      fileName: "test file 2",
                      folderId: "5f7763103a4af84960f86ae7",
                      categoryId: "6b7763103a4af84960f86ae2"
                  },
                  {
                      _id: "1c7763103a4af84960f86aa7",
                      fileName: "test file 3",
                      folderId: "5f7763103a4af84960f86ae6",
                      categoryId: "6b7763103a4af84960f86ae2"
                  },
            ]
        }
    }

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongodb-query


    【解决方案1】:

    你可以这样做:

    db.folders.aggregate([
      {
        "$lookup": {
          "from": "files",
          "localField": "_id",
          "foreignField": "folderId",
          "as": "files"
        }
      }
    ])
    

    下面是工作示例:https://mongoplayground.net/p/HaYRsK0ulXN

    【讨论】:

    • 是的,这工作文件夹中的所有文件。问题是我只需要指定的文件类别。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2020-09-04
    • 2021-04-23
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多