MongoDb: find deeply nested object with $lookup

前端 未结 1 355
孤独总比滥情好
孤独总比滥情好 2020-12-04 04:09

I have collection like this: collection name is - account. and it has sub-documents like account > buildings > gateways > devices.

{
    \"_id\" : ObjectI         


        
相关标签:
1条回答
  • 2020-12-04 04:42

    You can find nested device using $filter, $arrayElemAt and $let:

    device: {
        $let: {
            vars: {
                building: { 
                    $arrayElemAt: [ { $filter: { input: "$company_name.buildings", cond: { $eq: [ "$$this._id", "$buildingId" ] }} }, 0 ] 
                    }
            },
            in: {
                $let: {
                    vars: {
                        gateway: {
                            $arrayElemAt: [ { $filter: { input: "$$building.gateways", cond: { $eq: [ "$$this._id", "$gatewayId" ] }} }, 0 ] 
                        }
                    },
                    in: { $arrayElemAt: [ { $filter: { input: "$$gateway.devices", cond: { $eq: [ "$$this._id", "$deviceId" ] }} }, 0 ] }
                }
            }
        }
    }
    

    Full Solution

    0 讨论(0)
提交回复
热议问题