Display value within top level document of nested document field value in mongoDB

32 views Asked by At

This is the document from where i wanted to pull data from

{
        "_id" : ObjectId("635cbfee36945e4a79b0af70"),
        "EID" : 200,
        "EName" : "ram Kumar",
        "ESalary" : 50000,
        "EAddress" : {
                "AddL1" : "fjwh fhwi fijwo",
                "AddL2" : "uifwi efvhe",
                "City" : "Blr",
                "State" : "Karnataka",
                "PinCode" : 560103,
                "OfficeAddress" : {
                        "AddL1" : "bhr",
                        "State" : "Hyderabad",
                        "PinCode" : 125465,
                        "OfficeName" : "HCLN"
                }
        },
        "EFevMovieDetails" : [
                {
                        "MoveName" : "ROBO 1.0",
                        "WatchedDate" : "10/01/2022"
                },
                {
                        "MoveName" : "DDLJ",
                        "WatchedDate" : "01/01/2020"
                },
                {
                        "MoveName" : "Krish",
                        "WatchedDate" : "01/01/2015"
                }
        ]
}

expected result block

{
        "_id" : ObjectId("635cbfee36945e4a79b0af70"),
        "EID" : 200,
        "EName" : "ram Kumar",
        "ESalary" : 50000,
        "EAddressState" : "Karnataka"
        "EOfficeState" : "Hyderabad",
        "EOfficePinCode" : 125465,
        "EWantedToWatchAgainIfWeOffer" : "Krish" //MovieName must be available within the object "EFevMovieDetails"
}
1

There are 1 answers

1
Dhaval Italiya On

replace Model_name with your Model and to actual _id.

let data = await Model_name.findOne({_id: <Your _id>}).select({
"_id": 1,
"EID": 1,
"EName": 1,
"ESalary":1,
"EAddressState":"$EAddress.State",
"EOfficeState":"$EAddress.OfficeAddress.State",
"EOfficePinCode":"$EAddress.OfficeAddress.PinCode",
"EWantedToWatchAgainIfWeOffer":{"$last":"$EWantedToWatchAgainIfWeOffer.MoveName"}});
  
console.log(data)