我的文档中有两个对象数组。
{
"profileSpherestatus": [
{
"idf": "B002",
"completedPercentage": 100
},
{
"idf": "B003",
"completedPercentage": 90
},
{
"idf": "B004",
"completedPercentage": 100
}
]
"myGratificacions": [
{
"idb": "B003",
"gratification": 20
},
{
"idb": "B004",
"gratification": 30
}
]
}
如果 profileSpherestatus 数组中至少有一个对象,其中 idf 为“B002”,completedPercentage 为 100,并且没有“idb”:“B002”的满足,我想在 myGratifications 中添加一个新对象
新对象是:
newObject = {
"idb":"B002",
"gratification":10
}
这是我的管道:
[
{"$set": {
"myGratifications":
{"$cond": {
"if": {
"$and": [
{"profileSpherestatus":
{"$elemMatch": {"idf": "B002", "completedPercentage": 100}}
},
{"$not":
{"myGratifications":{"$elemMatch": {"idb": "B002"}}}
}
]
},
"then": {
"$concatArrays": ["$myGratifications",[newObject]]
},
"else": "$myGratifications"
}}
}}
]
但是 $elemMatch 不能在 $set 或 $addFields 内部使用。你能帮我吗?
$elemMatch
。
通过检查
$elemMatch
数组的 $size
替换第一个 $filter
条件。
将第二个
$elemMatch
条件替换为 $not
$in
。
db.collection.update({ /* match criteria */ },
[
{
"$set": {
"myGratificacions": {
"$cond": {
"if": {
"$and": [
{
$gt: [
{
$size: {
$filter: {
input: "$profileSpherestatus",
cond: {
$and: [
{
$eq: [
"$$this.idf",
"B002"
]
},
{
$eq: [
"$$this.completedPercentage",
100
]
}
]
}
}
}
},
0
]
},
{
"$not": {
$in: [
"B002",
"$myGratificacions.idb"
]
}
}
]
},
"then": {
"$concatArrays": [
"$myGratificacions",
[
{
"idb": "B002",
"gratification": 10
}
]
]
},
"else": "$myGratificacions"
}
}
}
}
])
请注意,您当前的更新查询中存在拼写错误,
myGratifications
字段在您的文档中不存在,应该是myGratificacions
。