简体   繁体   中英

How to query subdocuments using $lookup in mongodb?

I have a personal project and I am new in MongoDB aggregate function. I got the correct result querying two collections using $lookup but I want to modify the result and get my desired output.

Here is my Sample Collection

"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"
            },
        }
    }
]

I'm getting a correct result like this using $lookup and $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"
        }
      },
    }
  }
]

But I want my output like this. And I want to project userid and _id so I can get my desired output. Thanks you so much for helping


[
  {
    "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"
          }
      },
    }
  }
]

You can select first element from documents array by $arrayElemAt or $first (v4.4) operators after lookup stage,

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

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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