Mongo _id for subdocument array
I wish to add an _id as property for objects in a mongo array.
I assume:
{
g: [
{ _id: ObjectId(), property: '' },
// next
]
}
Type of structure for this question.
Is this good practice ?
Not normally. _id
s are unique identifiers for entities. As such if you are looking to add _id
within a sub-document object then you might not have normalised your data very well and it could be a sign of a fundamental flaw within your schema design.
Sub-documents are designed to contain repeating data for that document, i.e. the addresses or a user or something.
That being said _id
is not always a bad thing to add. Take the example I just stated with addresses. Imagine you were to have a shopping cart system and (for some reason) you didn't replicate the address to the order document then you would use an _id
or some other identifier to get that sub-document out.
Also you have to take into consideration linking documents. If that _id
describes another document and the properties are custom attributes for that document in relation to that linked document then that's okay too.
Are there any problems with indexing ?
An ObjectId
is still quite sizeable so that is something to take into consideration over a smaller, less unique id or not using an _id
at all for sub-documents.
For indexes it doesn't really work any different to the standard _id
field on the document itself and a unique index across the field should work across the collection (scenario dependant, test your queries).
NB: MongoDB will not add an _id
to sub-documents for you.
Related videos on Youtube
johnlemon
Updated on September 15, 2022Comments
-
johnlemon over 1 year
I wish to add an _id as property for objects in a mongo array.
Is this good practice ? Are there any problems with indexing ?
-
Eric over 11 yearsThe question is a little vague as it is. Can you give a little more details?
-
Sammaye over 11 yearsI don't think that link has anything to do with this question.
-
-
Sammaye almost 10 years@aioobe I think in this case yes I meant normalisation, it is a very old answer but I believe I meant about him not separating entities very well which would be normalisation.
-
Saitama over 6 yearsIf I create a mongodb object _id on a sub document, is that _id automatically unique across entire collection?
-
Sammaye about 6 yearsIn 90% of cases, yes, but time fragments can conflict however, MongoDB did something to fix that some time ago
-
Saitama about 6 years90% is really scary.. :s
-
deb over 3 yearsI'd like to add that Mongoose, on the other side, will automatically add a
_id
for each sub-document.