MongoDB Embedded Objects have no ID (null value) MongoDB Embedded Objects have no ID (null value) spring spring

MongoDB Embedded Objects have no ID (null value)


MongoDB CRUD operations (insert, update, find, remove) all operate on top-level documents exclusively -- although of course you can filter by fields in embedded documents. Embedded documents are always returned within the parent document.

The _id field is a required field of the parent document, and is typically not necessary or present in embedded documents. If you require a unique identifier, you can certainly create them, and you may use the _id field to store them if that is convenient for your code or your mental model; more typically, they are named after what they represent (e.g. "username", "otherSystemKey", etc). Neither MongoDB itself, nor any of the drivers will automatically populate an _id field except on the top-level document.

Specifically in Java, if you wish to generate ObjectId values for the _id field in embedded documents, you can do so with:

someEmbeddedDoc._id = new ObjectId();


In the context of a REST architecture it makes all the sense that nested docs have their own Ids.

  1. Persistence implementation should be independent from resource representation. As an API consumer I don't care if you are using mongo or mysql. If you a nest docs without id in mongo try to imagine how to change the persistence layer to a relational data base. Now do the same exercise having thought beforehand with an implementation independent approach. Modeling nested docs in a relational db, root and nested docs will be different entities/tables each with their own ids. The root could have a one to many relationship with the nested doc.
  2. I may need to access a nested doc directly instead of sequentially.I may not need absolute unique ids, like those issued by mongo, but I'll still need some local unique identifier. This is, unique within the root doc.

Having argued my point about the need of ids in nested docs @dcrosta has already given a correct answer on how to populate the _id field in mongo.

Hope this helps.


An _id is not set on subdocuments by default only on root docuemnts.

You will need to define a _id for your subdocuments on insert and update.