MongoDB
I know that if you have an array of subdocuments, and you index some field on those subdocuments, that field is only assured to be unique within the whole collection, but not within that single array.
Does the same apply to the _id property of those subdocuments? For example, if I have the following
{
_id: 'Parent ID',
subdocArray: [
{
_id: 'Child ID 1'
}
]
}
And I decide to add another child document to the array, is is assured that the _id field will be unique in the same way that it would be in a regular top-level document.
No, _id
has no special meaning to MongoDB in an array of subdocuments.
However, as asked here, you can enforce this desired restriction manually while adding elements to the array.
db.coll.update(
{_id: 'Parent ID', 'subdocArray._id': {$ne: 'Child ID 1'}},
{$push: {subdocArray: {_id: 'Child ID 1'}}})