Mongo _id for an array of subdocuments

I want to add the _id property as for the objects in the mongo array.

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

+8
mongodb
source share
1 answer

I want to add the _id property as for the objects in the mongo array.

I suppose:

{ g: [ { _id: ObjectId(), property: '' }, // next ] } 

The type of structure for this question.

Is this a good practice?

Not okay. _id are unique identifiers for objects. Thus, if you want to add _id to the subdocument object, you may not normalize your data very well, and this may be a sign of a fundamental flaw in the structure of your schema.

Subdocuments are intended to store duplicate data for this document, that is, addresses or user or something else.

What _id says is not always useful to add. Take the example that I just pointed out with the addresses. Imagine that you must have a shopping cart system and (for some reason) you did not replicate the address in the order document, then you would use _id or some other identifier to get this sub-document.

You should also consider linking documents. If this _id describes another document, and the properties are custom attributes for this document in relation to this related document, then this is also good.

Are there any problems with indexing?

An ObjectId is still quite significant, so it should be taken into account with a smaller, less unique identifier or not use _id for subdocuments at all.

For indexes, it really does not differ from the standard field _id the document itself, and the unique index in the field should work in the collection (depending on the script, check your queries).

NB: MongoDB will not add _id to subdomains for you.

+16
source share

All Articles