Reputation: 4476
I'm using Morphia with MongoDB 2.4.9 and I'm looking for a way of querying references of a document in one query.
I read the several patterns in the documentation. I used the following to organize my e-commerce website. I have 3 collections :
Category
Product
that has a @Reference of Category
ProductOccurence
that has a @Reference of Product
A common query that I want to do is :
Find all product occurences of a category ordered by date ascending and status enabled.
Is there a way of doing this without having to do something like this :
for (Product product : findProductsByCategory(category)) {
for (ProductOccurence o : findOccurencesByProduct(product)) {
ocurrences.add(o);
}
}
The main problem of doing this in Java with multiple queries is that I can't apply my order by date to the entire list of occurences.
And I don't want to embed product occurences in product and product in categories because the number of products will grow and that will lead to a large document size...
Upvotes: 2
Views: 99
Reputation: 3760
Finding all products for a given category should be a single query. You can take the resulting set of products and use it in a $in query to find all occurences of those products. That would be a single query as well. The $in operator is optimized so that it takes little more time than a query for only a single product, even for very large sets of products. If you have a suitable compound key on product, date, and status enabled, then MongoDB should be able to use that for sorting too. If the result set is not too large, sorting could also be done within the application easily.
Upvotes: 2