Nemůžete použít "$match" s objektovou metodou po "$lookup", protože návratová hodnota "$lookup" jsou hodnoty pole. Raději přidejte funkci "$unwind" po vyhledání a pak ji seskupte.
Příklad dotazu
db
.album
.aggregate([
{
$lookup:{
from:"photo",
localField:"_id",
foreignField:"album_id",
as:"photo"
}
},
{
preserveNullAndEmptyArrays : true,
path : "$photo"
},
{
$match:{
"photo.flag": 1
}
},
{
$group : {
_id : {
id : "$_id",
album_name: "$album_name",
album_description: "$album_description",
emoji_id: "$emoji_id"
},
photo: {
$push : "$photo"
}
}
}
{
$lookup:{
from:"emoji",
localField:"_id.album_emoji",
foreignField:"_id",
as:"emoji"
}
},
{
$project:{
album_name:"$album_name",
album_description:"$album_description",
emoji:"$emoji",
photo:"$photo",
total_photos: {$size: "$photo"}
}
}
])
Nebo použijte "$filter".
db
.album
.aggregate([
{
$lookup:{
from:"photo",
localField:"_id",
foreignField:"album_id",
as:"photo"
}
},
{
$project: {
id : "$_id",
album_name: "$album_name",
album_description: "$album_description",
emoji_id: "$emoji_id",
photo: {
$filter : {
input: "$photo",
as : "photo_field",
cond : {
$eq: ["$$photo_field.flag",1]
}
}
}
}
},
{
$lookup:{
from:"emoji",
localField:"album_emoji",
foreignField:"_id",
as:"emoji"
}
},
{
$project:{
album_name:"$album_name",
album_description:"$album_description",
emoji:"$emoji",
photo:"$photo",
total_photos: {$size: "$photo"}
}
}
])