$lookup aggregation failed to display array value

Viewed 70

I'm working with MongoDB and I've 2 collections.

data collection ["user-profile"]

{ 
    "_id" : ObjectId("60650e6fc4b4603e1e78bb23"), 
    "firstName" : "Luthfan", 
    "lastName" : "Difiesa", 
    "mobile" : "86742633497", 
    "gender" : "male",
    "createdOn" : ISODate("2021-04-22T05:26:07.428+0000"), 
    "updatedOn" : ISODate("2021-04-22T05:26:55.218+0000")
}

data collection ["user-wishlist"]

{ 
    "_id" : ObjectId("60650e7a1a4a817a1dd0a29c"), 
    "userId" : "86742633497", 
    "contents" : [
        {
            "_id" : ObjectId("5ef9d2da228f840bbd41649c"), 
            "name" : "Kelas 11"
        }
    ]
}

expected output:

{ 
    "_id" : ObjectId("60650e6fc4b4603e1e78bb23"), 
    "firstName" : "Luthfan", 
    "lastName" : "Difiesa", 
    "mobile" : "86742633497", 
    "gender" : "male",
    "contents" : [
        {
            "_id" : ObjectId("5ef9d2da228f840bbd41649c"), 
            "name" : "Kelas 11"
        }
    ]
}

Here's the query:

db.getCollection("user-profile").aggregate(
    [ 
        { 
            "$lookup" : { 
                "from" : "user-wishlist", 
                "localField" : "mobile", 
                "foreignField" : "userId", 
                "as" : "contents"
            }
        }
    ], 
    { 
        "allowDiskUse" : false
    }
);

But the result is like this:

{ 
    "_id" : ObjectId("60650e6fc4b4603e1e78bb23"), 
    "firstName" : "Luthfan", 
    "lastName" : "Difiesa", 
    "mobile" : "86742633497", 
    "gender" : "male",
    "contents" : [

    ]
}

is't because of collection name using special character or type data from foreign or localField? thank u...

1 Answers

Your query looks good, just need add a stage after lookup to achieve your desire result,

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

Playground

Related