![](/img/trans.png)
[英]Get result based on property of another document from one document in MongoDB
[英]Mongodb get specific properties in the aggregate result from a document
我對如何使用聚合來獲得非常特定類型的結果有點迷茫。 我的數據庫文檔具有以下格式
{
_id: 122434
houseDetails: {
hasBedroom: {
flag: true,
},
hasKitchen: {
flag: false
},
hasBalcony: {
flag: false
},
hasFoyer: {
flag: true
},
}
}
(這是一個文檔結構的基本示例,細節不同)
我正在嘗試查詢嵌套houseDetails
屬性為真的所有文檔。 所以最后我希望結果看起來像
{
_id: 122434,
houseDetails: [hasBedroom, hasFoyer]
}
我可以使用 $match 來查找至少有一個屬性為 true 的所有文檔,但我似乎不知道如何僅將值為 true 的名稱投影到數組中。
一種選擇是:
$objectToArray
從鍵和值創建一個數組$filter
它只保留true
值$map
格式化項目db.collection.aggregate([
{$project: {houseDetails: {$objectToArray: "$houseDetails"}}},
{$project: {
houseDetails: {
$filter: {
input: "$houseDetails",
cond: {$eq: ["$$this.v.flag", true]}
}
}
}
},
{$project: {
houseDetails: {
$map: {
input: "$houseDetails",
in: "$$this.k"
}
}
}
}
])
看看它在操場上的例子是如何工作的
您也可以使用$reduce
僅分兩步完成:
db.collection.aggregate([
{$project: {houseDetails: {$objectToArray: "$houseDetails"}}},
{$project: {
houseDetails: {
$reduce: {
input: "$houseDetails",
initialValue: [],
in: {
$setUnion: [
"$$value",
{$cond: [{$eq: ["$$this.v.flag", true]}, ["$$this.k"], []]}
]
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.