在mongoDB中显示嵌套文档字段值的顶层文档中的值

ddrv8njm  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(156)

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"
}
6fe3ivhb

6fe3ivhb1#

//将Model_name替换为您的模型并替换为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)

相关问题