如何在 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(v4.4) 运算符 select 来自 documents 数组的第一个元素,

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

Playground