Anda hanya perlu menambahkan filter di $addFields
kedua Anda tahap yang Anda filter roomTypes
dan tahapan lainnya akan sama, cukup sorot kode baru di bawah ini dari mulai komentar dan akhiri komentar,
$reduce
untuk mengulang looproomDetails.description
array $cond untuk mencocokkan lokal dan mengembalikan hasil kecocokan ke nilai, proses yang sama untukroomDetails.title
array, dan gabungkan 2 bidang yang diperbarui ini dengan objek saat ini menggunakan$mergeObjects
{
$addFields: {
roomTypes: {
$map: {
input: "$roomTypes",
in: {
$mergeObjects: [
"$$this",
{
Mulai:
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"
]
}
}
}
}
]
},
~Akhir~
available: {
$reduce: {
input: "$$this.capacity",
initialValue: 0,
in: {
$cond: [
{ $eq: ["$$this.cruiseID", "$cruiseID"] },
"$$this.available",
"$$value"
]
}
}
}
}
]
}
}
}
}
}
Dalam opsi umum, saya telah menjawab pertanyaan referensi Anda anda dapat menggunakan fungsi yang sama seperti,
function languageFilter(inputField, locale) {
return {
$reduce: {
input: inputField,
initialValue: "",
in: {
$cond: [{ $eq: ["$$this.locale", locale] }, "$$this.value", "$$value"]
}
}
};
}
Permintaan terakhir Anda adalah:
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
}
}
]);