我使用MongoDB中存储的子类别在类别子类别和项目。我想用一个项目获取的主要类别。我怎样才能做到这在Spring数据,而无需一个双向参考的最简单的方法?
class Category {
private String id;
//some other attributes
@DbRef
List<Category> subCategories = new ArrayList<>();
@DbRef
List<Item> items = new ArrayList<>();
}
在DB的分类收集看起来是这样的:
{
id: 1,
subcategories: [
2, 3
]
},
{
id: 2,
items: [
001
]
}
我想通过提供ITEMID 001(这是在相关文件集合中的项),通过子类别2,而不承担连接的深度,以找到与ID 1的类别。
我宁愿使用Spring数据仓库的智能方法命名偷懒的方法,像Category findBySubCategoriesItems(Item item)
但@Query
也非常感谢!
编辑:我可以找到的itemId从MongoDB的控制台子类,但我不知道如何递归加紧根类别。这是我的查询:
db.category.find({ items: { id: ObjectId("someItemId") } })
我试着去周围的其他方式,通过这样的项目获得顶级类别和过滤:category.*.items.id : someItemId
但不幸的是通配符“任何深度”的查询不被支持,因为它在https://jira.mongodb.org/browse/SERVER-267的既定
编辑2:我一直在阅读有关GraphLookup但据我的理解,它只能找到根类,如果父母关系设置,并且只有当孩子的设置不能与它进行操作。
Graphlookup肯定是要走的路,假设两个集合名称是“项目”和“类别”,
db.items.aggregate([
{
// find the item in items collection
$match: {
items: '001'
},
},
// recursively find the categories starting from matched item
{
$graphLookup: {
from: "categories",
startWith: "$id",
connectFromField: "id",
connectToField: "subcategories",
as: "categories",
depthField: "level"
}
},
// get only the root node (this is optional, basically if you skip the below stage, you'll get the entire recursive category list along with the matched item)
{
$project: {
root_category: {
$filter: {
input: "$categories",
as: "category",
cond: {
$eq: [
"$$category.level",
{
$max: "$categories.level"
}
]
}
}
}
}
}
])