I am trying to update embedded doc only when matching condition is true but its inserting even condition not seems true. May be I am missing something here.
Sample mongo playground
I dont want to insert role if matching role is already there.
That I have done with aggregation pipeline. But here I was trying with simple update with elemmatch filter for another scenario and trying to understand why it’s not working in this case.
In case you still need some insight about this playground.
1 - if roles is null, $push will fail
mongosh> c.find( { _id : 1 })
{ _id: 1, roles: null }
mongosh> c.updateOne( { _id : 1 } , { "$push" : { "roles" : [ { _id : 101 , name : 201 }]}})
MongoServerError: The field 'roles' must be an array but is of type null in document {_id: 1}
Starting with 4.2 you could handle this case using a $set stage with $cond to replace roles:null with roles:[ ].