我正在嘗試通過 react chartjs 顯示 MongoDB 聚合結果。在聚合中,我可以通過 set 運算子洗掉一個值為靜態的欄位。有沒有辦法通過值是動態的關聯洗掉第二個欄位?在下面的示例中,{"A": "N"}表示易于被設定運算子洗掉的欄位,而{"A_count":1}表示我試圖洗掉的相應動態欄位。
開始聚合輸出
[{
"_id":"Fubar",
"A_set":[{"A":"Y"},{"A":"N"}],
"A_count_set":[{"A_count":0},{"A_count":1}]
}]
靜態欄位移除的設定操作
{$set: {
A_set: {
$filter: {
input: "$A_set",
as: "x",
cond: { "$ne": [ "$$x", {"A":"N"}] }
}
}
}}
當前聚合輸出
[{
"_id":"Fubar",
"A_set":[{"A":"Y"}],
"A_count_set":[{"A_count":0},{"A_count":1}]
}]
目標聚合輸出
[{
"_id":"Fubar",
"A_set":[{"A":"Y"}],
"A_count_set":[{"A_count":0}]
}]
uj5u.com熱心網友回復:
$project合并兩個位置相同的陣列$set過濾器陣列$addFields恢復原始陣列$project洗掉合并陣列
總計的
db.collection.aggregate([
{
$project: {
anotherValue: {
$map: {
input: {
$range: [
0,
{
$size: "$A_set"
}
]
},
as: "idx",
in: {
$mergeObjects: [
{
$arrayElemAt: [
"$A_set",
"$$idx"
]
},
{
$arrayElemAt: [
"$A_count_set",
"$$idx"
]
}
]
}
}
}
}
},
{
$set: {
anotherValue: {
$filter: {
input: "$anotherValue",
as: "x",
cond: {
"$ne": [
"$$x.A",
"N"
]
}
}
}
}
},
{
$addFields: {
"A_set": {
$map: {
input: "$anotherValue",
as: "a",
in: {
"A": "$$a.A"
}
}
},
"A_count_set": {
$map: {
input: "$anotherValue",
as: "a",
in: {
"A_count": "$$a.A_count"
}
}
}
}
},
{
"$project": {
"anotherValue": 0
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/359656.html
