簡體   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