Stačí přidat filtr do druhého $addFields
fázi, kterou filtrujete roomTypes
a zbytek fází by byl stejný, jen zvýrazněný nový kód níže od počátečního komentáře a koncového komentáře
$reduce
iterovat smyčkuroomDetails.description
pole $cond, aby odpovídalo local a vrátilo výsledek shody na hodnotu, stejný proces proroomDetails.title
pole a sloučit tato 2 aktualizovaná pole s aktuálním objektem pomocí$mergeObjects
{
$addFields: {
roomTypes: {
$map: {
input: "$roomTypes",
in: {
$mergeObjects: [
"$$this",
{
Začátek:
roomDetails: {
$mergeObjects: [
"$$this.roomDetails",
{
description: {
$reduce: {
input: "$$this.roomDetails.description",
initialValue: "",
in: {
$cond: [
{ $eq: ["$$this.locale", "pl"] },
"$$this.value",
"$$value"
]
}
}
},
title: {
$reduce: {
input: "$$this.roomDetails.title",
initialValue: "",
in: {
$cond: [
{ $eq: ["$$this.locale", "pl"] },
"$$this.value",
"$$value"
]
}
}
}
}
]
},
~Konec~
available: {
$reduce: {
input: "$$this.capacity",
initialValue: 0,
in: {
$cond: [
{ $eq: ["$$this.cruiseID", "$cruiseID"] },
"$$this.available",
"$$value"
]
}
}
}
}
]
}
}
}
}
}
V obecné možnosti jsem odpověděl ve vaší referenční otázce můžete použít stejnou funkci jako,
function languageFilter(inputField, locale) {
return {
$reduce: {
input: inputField,
initialValue: "",
in: {
$cond: [{ $eq: ["$$this.locale", locale] }, "$$this.value", "$$value"]
}
}
};
}
Váš poslední dotaz by byl:
let locale = "pl";
db.cs.aggregate([
{ $match: { cID: "00001" } },
{
$lookup: {
from: "rooms",
localField: "roomTypes.roomID",
foreignField: "roomID",
as: "roomTypes"
}
},
{
$addFields: {
title: languageFilter("$title", locale),
description: languageFilter("$description", locale),
roomTypes: {
$map: {
input: "$roomTypes",
in: {
$mergeObjects: [
"$$this",
{
roomDetails: {
$mergeObjects: [
"$$this.roomDetails",
{
description: languageFilter("$$this.roomDetails.description", locale),
title: languageFilter("$$this.roomDetails.title", locale)
}
]
},
available: {
$reduce: {
input: "$$this.capacity",
initialValue: 0,
in: {
$cond: [
{ $eq: ["$$this.cruiseID", "$cruiseID"] },
"$$this.available",
"$$value"
]
}
}
}
}
]
}
}
}
}
},
{
$project: {
_id: 0,
"roomTypes": { _id: 0 },
"roomTypes.capacity": 0
}
}
]);