Filtering one collection using DBRef from a second one that refers to another third

Hello @Javier_Blanco,

You can do an aggregation $lookup on the sensorsData and devices collections. The query can look like this (a lookup of Join Conditions and Uncorrelated Sub-queries):

db.sensorsData.aggregate([
  { 
    $match: { idSensor : NumberLong("3") } 
  },
  { 
    $lookup: {
        from: "devices",
        let: { sensorsDeviceId: "$idDevice" },
        pipeline: [ 
            { 
                $match: { 
                    $expr: {
                        $and: [
                            { $eq: [ "$$sensorsDeviceId", "$_id" },
                            { $eq: [ "$group", NumberLong("11") }
                        ]
                    }
                }
            }
       ],
       as: "group_sensors_data"
    }
  },
]) 

Let me know how this works out.

1 Like