I have a question regarding MongoDB with Spring Data. I have these domain classes:
@Document
public class Deal {
@Id
private ObjectId _id;
priv
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();
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.
Mongo does not create or need _id
s on embedded documents. You can add an _id
field if you want - I have done it.
@Document
public class Location {
@Id
private ObjectId _id;
public Location() {
this._id = ObjectId.get();
}
}
@Document
public class User {
@Id
private ObjectId _id;
public User() {
this._id = ObjectId.get();
}
}
This works great for me.
In the context of a REST architecture it makes all the sense that nested docs have their own Ids.
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.