I am trying to update the memberOfGroups array only if none of the element has the matching value. not sure why its taking even the condition is not satisfy, I can not give condition in find and use positional because I need to update more array inside document. so I need to utilize aggregation pipeline.
I can not use addtoset as there may be few field which are different , i can rely only on unique id.
Please try here.
Hello @Shyam_Sohane ,
I would suggest you use a normal query instead of update with aggregation pipeline, here is a query,
check query if memberOfGroups._id
is not present
$push
to add element in memberOfGroups
array
db.principals.update(
{
_id: "67448af8-a68b-4d08-8948-2cddca57d708",
"memberOfGroups._id": {
$ne: "ba93384d-d18a-4b36-9a24-7d3ebb1619d8"
}
},
{
$push: {
memberOfGroups: {
_id: "ba93384d-d18a-4b36-9a24-7d3ebb1619d8",
name: "test group"
}
}
}
)
Playground
Fixed issues in your query,
Condition should check array by $in
operator because $memberOfGroups._id
returns an array of _ids
True part return the current existing value of $memberOfGroups
False part return concat array
db.principals.update(
{ _id: "67448af8-a68b-4d08-8948-2cddca57d708" },
[{
$set: {
memberOfGroups: { $ifNull: ["$memberOfGroups", []] }
}
},
{
$set: {
memberOfGroups: {
$cond: [
{ $in: ["ba93384d-d18a-4b36-9a24-7d3ebb1619d8", "$memberOfGroups._id"] },
"$memberOfGroups",
{
$concatArrays: [
"$memberOfGroups",
[
{
_id: "ba93384d-d18a-4b36-9a24-7d3ebb1619d8",
name: "test group"
}
]
]
}
]
}
}
}
])
Playground
Awesome, thanks Vishal. I was comparing opposite. Thanks.
system
(system)
Closed
August 2, 2022, 12:46pm
4
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.