Given a couple of collecitons:
1.- USERS
{
name: ...
id: ...
city: ...
age: ...
otherdata: ...
}
2.- PETS
{
You can use $filter array aggregation operator on pets
array that is produced by your $lookup
stage.
To output pets older than 1 year use
db.users.aggregate([
{
$lookup:
{
from: "pets",
localField: "id",
foreignField: "owner",
as: "pets"
}
},
{
$project:
{
name: 1,
pets:
{
$filter:
{
input: "$pets",
as: "pet",
cond: { $gte: [ "$$pet.age", 1 ] }
}
}
}
}
]);
To output the oldest pets simply replace cond
field of $filter
operator in the previous aggregation pipeline with
cond: { $eq: [ "$$pet.age", { $max: "$pets.age" } ] }