Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo _id for subdocument array

Tags:

mongodb

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

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

like image 998
johnlemon Avatar asked Nov 20 '12 11:11

johnlemon


1 Answers

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.

like image 100
Sammaye Avatar answered Oct 14 '22 01:10

Sammaye