Mongo Playground

Configuration

db={"principals":[{"_id":"67448af8-a68b-4d08-8948-2cddca57d708","identity":{"_id":"7.26Demo@test.com","type":"Email"},"type":"User","links":[{"linkType":"Org","linkPath":"0923689a-e009-4d67-8db5-5ba40f840bf3/facd3c31-dbfd-4097-9a27-0d862bb0c8e9","status":"Activated","createdOn":{"$date":"2022-07-26T14:49:38.780Z"},"createdBy":""}],"memberOfGroups":[{"_id":"ba93384d-d18a-4b36-9a24-7d3ebb1619d7","name":"test group"},{"_id":"ba93384d-d18a-4b36-9a24-7d3ebb1619d8","name":"test group"}],"roles":[{"_id":"ba93384d-d18a-4b36-9a24-7d3ebb1619d7","name":"test group","sources":[{"type":"group","linkType":"app","groupId":"ba93384d-d18a-4b36-9a24-7d3ebb1619d7"}]}]}]}

Query

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"}]]}]}}}])

Result