簡體   English   中英

如何在 mongodb 中使用 $lookup 查詢子文檔?

[英]How to query subdocuments using $lookup in mongodb?

我有一個個人項目,我是 MongoDB 聚合函數的新手。 我使用$lookup查詢兩個集合得到了正確的結果,但我想修改結果並獲得我想要的輸出。

這是我的樣本集

"users":  [
    {
        "_id" : "60499e72b60a8819c4e0fa03"
        "LastName": "Doe"
        "FirstName" "John"
    }
]

"userdocuments":  [ 
    {
        "_id":  "61025b9f890bacbe8f450f6a",
        "userid": 60499e72b60a8819c4e0fa03,
        documents: {
            documentOne: {
                documentTitle: "This is Document One"
            },
            documentTwo: {
                documentTitle: "This is Document Two"
            },
            documentThree: {
                documentTitle: "This is Document Three"
            },
        }
    }
]

我使用$lookup$unwind https://mongoplayground.net/p/k1lmvJg-tB7得到了這樣的正確結果

[
  {
    "FirstName": "John",
    "LastName": "Doe",
    "_id": "60499e72b60a8819c4e0fa03",
    "documents": {
      "_id": "61025b9f890bacbe8f450f6a",
       "userid": "60499e72b60a8819c4e0fa03"
      "documents": {
        "documentOne": {
          "documentTitle": "This is Document One"
        },
        "documentThree": {
          "documentTitle": "This is Document Three"
        },
        "documentTwo": {
          "documentTitle": "This is Document Two"
        }
      },
    }
  }
]

但我希望我的輸出是這樣的。 我想投影userid_id以便我可以得到我想要的輸出。 非常感謝你的幫助


[
  {
    "FirstName": "John",
    "LastName": "Doe",
    "_id": "60499e72b60a8819c4e0fa03",
    "documents": {
          "documentOne": {
            "documentTitle": "This is Document One"
          },
          "documentThree": {
            "documentTitle": "This is Document Three"
          },
          "documentTwo": {
            "documentTitle": "This is Document Two"
          }
      },
    }
  }
]

您可以在查找階段后通過$arrayElemAt$first ( $arrayElemAt ) 運算符從documents數組中選擇第一個元素,

  {
    $addFields: {
      Documents: {
        $arrayElemAt: ["$Documents.documents", 0]
      }
    }
  }

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM