Mongo _id for subdocument array

12,878

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. _ids 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.

Share:
12,878

Related videos on Youtube

johnlemon
Author by

johnlemon

Updated on September 15, 2022

Comments

  • johnlemon
    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
      Eric over 11 years
      The question is a little vague as it is. Can you give a little more details?
    • Sammaye
      Sammaye over 11 years
      I don't think that link has anything to do with this question.
  • Sammaye
    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
    Saitama over 6 years
    If I create a mongodb object _id on a sub document, is that _id automatically unique across entire collection?
  • Sammaye
    Sammaye about 6 years
    In 90% of cases, yes, but time fragments can conflict however, MongoDB did something to fix that some time ago
  • Saitama
    Saitama about 6 years
    90% is really scary.. :s
  • deb
    deb over 3 years
    I'd like to add that Mongoose, on the other side, will automatically add a _id for each sub-document.