I'm using MongoDB to store subcategories in categories, and items in the subcategories. I'd like to retrieve the main category by an item. How can I do that in Spring Data the easiest way without having a bi-directional reference?
class Category {
private String id;
//some other attributes
@DbRef
List<Category> subCategories = new ArrayList<>();
@DbRef
List<Item> items = new ArrayList<>();
}
In the DB the Categories collection looks something like:
{
id: 1,
subcategories: [
2, 3
]
},
{
id: 2,
items: [
001
]
}
I'd like to find the category with ID 1 by providing the itemID 001 (which is an item in the Items collection), through the subcategory 2, without assuming the depth of connections.
I'd prefer the lazy way with Spring Data Repository's smart method naming, something like Category findBySubCategoriesItems(Item item)
but @Query
is also much appreciated!
Edit: I can find the subCategory from MongoDB console by itemId but I don't know how to recursively step up to the root category. This is my query:
db.category.find({ items: { id: ObjectId("someItemId") } })
I tried to go the other way around, getting the top level categories and filtering by the item like this: category.*.items.id : someItemId
but unfortunately the wildcard "any depth" query is not supported, as it's stated in https://jira.mongodb.org/browse/SERVER-267
Edit 2: I've been reading about GraphLookup but as far as I understand, it could only find the root category if the parent relation was set, and can't operate with it when only the childs are set.