如果當前用戶具有權限或不基于電子郵件存在于物件陣列中,我正在嘗試添加一個屬性。
我的輸入資料如下所示。
[
{
nId: 0,
children0: [
{
nId: 3,
access: [
{
permission: "view",
email: "[email protected]"
}
]
},
{
nId: 4,
access: [
{
permission: "view",
email: "[email protected]"
}
]
}
]
}
]
https://mongoplayground.net/p/xZmRGFharAb
[
{
"$addFields": {
"children0": {
"$map": {
"input": "$children0.access",
"as": "accessInfo",
"in": {
"$cond": [
{
"$eq": [
"$$accessInfo.email",
"[email protected]"
]
},
{
"$mergeObjects": [
"$$accessInfo",
{
"hasAccess": true
}
]
},
{
"$mergeObjects": [
"$$accessInfo",
{
"hasAccess": false
}
]
},
]
}
}
}
}
}
]
我也嘗試了以下答案,但這也沒有合并物件。
https://mongoplayground.net/p/VNXcDnXl_sZ
uj5u.com熱心網友回復:
嘗試這個:
db.collection.aggregate([
{
"$addFields": {
"children0": {
"$map": {
"input": "$children0",
"as": "accessInfo",
"in": {
nId: "$$accessInfo.nId",
access: "$$accessInfo.access",
hasAccess: {
"$cond": {
"if": {
"$ne": [
{
"$size": {
"$filter": {
"input": "$$accessInfo.access",
"as": "item",
"cond": {
"$eq": [
"$$item.email",
"[email protected]"
]
}
}
}
},
0
]
},
"then": true,
"else": false
}
}
}
}
}
}
}
])
在這里,我們使用 one$map
進行回圈children0
,然后過濾access
陣列以僅包含具有匹配電子郵件的元素。如果過濾后的陣列非空,我們設定hasAccess
為 true。
游樂場鏈接。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/504008.html
上一篇:如何使用打字稿匯出貓鼬模型?