我正在嘗試過濾嵌套的物件陣列,我只需要匹配的屬性物件。面臨獲得我的聚合的預期輸出的問題。在示例資料中,頂層有更多欄位,但此聚合輸出不需要這些欄位。
樣本資料。從上面下面的資料,只需要過濾subscribed milestone status并回傳。里程碑物件的最后一個索引始終具有我們需要檢查和過濾的更新屬性。
{
active: 'true',
time:'',
unified_invitees: [
{
_id: 1,
milestone_status: [
{
milestone:"draft"
},
{
milestone:"deleted"
},
]
},
{
_id: 2,
milestone_status: [
{
milestone:"draft"
},
{
milestone:"deleted"
},
]
},
{
_id: 3,
milestone_status: [
{
milestone:"draft"
},
{
milestone:"subscribed"
},
]
},
]
}
我嘗試了以下解決方案,但似乎沒有按預期作業。
添加欄位
{
"invitee":{
$filter: { input: "$unified_invitees.milestone_status", cond: { $eq: [ "$$this.milestone", "subscribed" ] } }
}
}
{
"unified_invitees": {
"$arrayElemAt": [
{
"$filter": {
"input": "$unified_invitees",
"as": "comp",
"cond": {
"$ne": [ "$$comp.milestone_status.milestone", "deleted" ]
}
}
}, 0
]
}
}
過濾器 地圖
{
"documents": {
$map: {
"input": "$unified_invitees",
"as": "d",
"in": {
"milestone_status": {
$filter: {
"input": "$$d.milestone_status",
"as": "s",
"cond": {
$eq: [
"$$s.milestone",
"subscribed"
],
}
}
}
}
}
}
}
uj5u.com熱心網友回復:
You can use the $anyElementTrue operator along with $map to filter the inner array:
db.collection.aggregate([
{
$addFields: {
unified_invitees: {
$filter: {
input: "$unified_invitees",
as: "un",
cond: {
$anyElementTrue: {
$map: {
input: "$$un.milestone_status",
as: "ms",
in: { $eq: [ "$$ms.milestone", "subscribed" ] }
}
}
}
}
}
}
}
])
The role of $map operator here is to return an array of boolean values representing whether each milestone_status is set to subscribed.
MongoDB Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/530485.html
上一篇:如何在回圈中命令Ajax呼叫
