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