繁体   English   中英

Mongodb - 如何在第二个文档中按键连接两个文档并将子文档作为数组合并到父文档

[英]Mongodb - How to Join two documents by key in second document and merge child documents as array to parent document

我有三个用 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"
    },
]

当我在文件文档中按 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"
                  },
            ]
        }
    }

你可以这样做:

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

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

暂无
暂无

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

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