Mongo _id for subdocument array

前端 未结 1 1511
小蘑菇
小蘑菇 2021-01-17 10:39

I wish to add an _id as property for objects in a mongo array.

Is this good practice ? Are there any problems with indexing ?

1条回答
  •  醉梦人生
    2021-01-17 10:57

    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.

    0 讨论(0)
提交回复
热议问题