using document oriënted database mongodb and the Object Document Mapper (ODM) morphia
Lets say we have 3 different classes; Object
, Category
and Action
.
These object are all stored in the collections; objects, categories and actions.
Category
and Action
are references of Object
@Entity("objects")
public class Object {
@Id
@Property("id")
private ObjectId id;
@Reference
private Category category;
private Action action;
...
}
@Entity("categories")
public class Category {
@Id
public String categoryTLA;
public String categoryName;
...
}
@Entity("actions")
public class Action implements BaseEntity {
@Id
public String action;
public int accesLevel;
...
}
The documents with the current implementation are stored like:
Is it possible to store 2 different Objects, in this case Category
and Action
, in one collection, like shown in the next example? Both with their own identification!
Absolutely, it's possible to store multiple types of documents in a single collection. In fact, that's one of the strengths of a document oriented database like Mongo. However, you may not want to combine them without considering some issues (positive and negative):
Action
can't be a Category
for example. If you did the equivalent of FindAll
and there were multiple document types, unless the deserializer can evaluate the document structure before deserialization starts, your code may not work as desired.Action
has an index that is unqiue from Category
, all documents inserted into the collection containing both will run through the indexer, for all indexes defined in the collection. That can impact performance depending on the nature of the indexes. This means that all documents in the collection will be indexed regardless of whether the index makes sense. This is often a compelling reason to not combine multiple document types that do not share common indexing traits.Unless you need to do specific types of queries that require all documents to be in a common collection, I'd likely leave them in separate collections, especially if you plan on using custom indexes for various document types/schemas.