I have a mongo document like so:
{ "_id" : "testing", "member_ids" : [ { "id" : 1, "name": "Joe" }, { "id" : 2, "name": "Joseph" } ] }
I've created a unique index on the collection:
When I insert a new document with a
member_ids.id value that matches either 1 or 2 - the two present in the example document above - I get the error I expect, telling me that a document with that value already exists.
However, when I use $push with an update the constraint does NOT work:
db.audience_members.updateOne( { '_id': 'testing' }, { $push: { member_ids: { 'id': 1, 'name': 'Joe' } } } )
Now it looks like:
{ "_id" : "testing", "member_ids" : [ { "id" : 1, "name": "Joe" }, { "id" : 2, "name": "Joseph" }, { "id" : 1, "name": "Joe" } ] }
Does anyone know why the updateOne() call with $push not being constrained by the unique index?
Thanks!