如何解决Mongodb:对同一集合进行查找,并使用单个查询在父类别数组中获取子类别
这是类别集合的架构,其中存储了类别,子类别以及子类别的其他子类别。
mongoose.Schema({
name:{ type: Array,required: true},//It is an array because name can be in multiple languages
path:{ type: String,// All parent categories in an order to have immediate parent at the end
parent: { type: String,required: true}
});
我在所有三个字段上都添加了索引。现在,要求是什么-需要使嵌套在父类别数组中的所有子类别都作为单个查询的结果返回。
对于根目录类别,parent
具有'/'
,而path
是由'/'分隔的ID,直到直接父级。
我尝试过的是,通过传递_id
来获得父类别的所有子类别,例如-
categoryModel.find({parent: /^\/documentId/})
但是,我希望结果是所有嵌套了子类别的父类别。该怎么做?
预期输出-
[
{
_id: '1',name: 'MainCategory1',path: '/'
parent: '/',children: [
{
_id: '3',name: 'SubCategory3',parent: '1',path: '/1'
},]
},{
_id: '2',name: 'MainCategory2',children: [
{
_id: '5',name: 'SubCategory5',parent: '2',path: '/2',children: [
{
_id: '7',name: 'SubCategory7',parent: '5',path: '/2/5',children: [
{
_id: '9',parent: '7',path: '/2/5/7',}]
},]
},]
解决方法
我使用聚合$graphlookup
和$match
得到了结果,尽管它的格式不正确。我需要的格式是在获得查询响应后构建的。这是我的查询
{ $match: {parent : '/'}},{
$graphLookup: {
from: "category",startWith: "$_id",connectFromField: "_id",connectToField: "parent",depthField: "depth",as: "children"
},},
这是我从上述查询中得到的响应
[{
"_id":"1","name":"category1","parent":'/',"children":[
{
"_id":"3","name":"Sub-Category1","parent":"1","depth":0
}
]
},{
"_id":"2","name":"Category2","children":[
{
"_id":"4","name":"Sub-Category2","parent":"2","depth":0
},{
"_id":"5","name":"Sub-Category3","parent":"4","depth":1
}
]
}]
depth 0,depth 1是子类别相对于父类别的级别。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。