从添加到具有层次结构的mongodb的类别和子类别创建json对象

时间:2017-01-26 11:41:18

标签: mongodb mongoose mongodb-query aggregation-framework

我使用node在mongoDB中创建了类别,为每个插入添加了父属性以确定哪个是父类别。

[{ _id: 5889a06f274afdfd6f2bf249,
    cat_id: 1,
    title: 'Parent Category',
    description: '',
    parent: null,
    status: 1}]

[{ _id: 5889a06f274afdfd6f2bf249,
    cat_id: 1,
    title: 'Child Category',
    description: '',
    parent: 1,
    status: 1}]

现在,当我使用mongoDB的db.find()方法查询时,输出json应该使用node。

{
  obj: [
  { 
    _id: "5889a06f274afdfd6f2bf249",
    cat_id: 1,
    title: "Parent Category",
    description: "",
    parent: null,
    status: 1, 
    subcategories: [
      { 
        _id: "5889a06f274afdfd6f2bf249",
        cat_id: 1,
        title: "Child Category",
        description: "",
        parent: 1,
        status: 1

      }
    ]

  }
]}

1 个答案:

答案 0 :(得分:2)

您可以尝试以下内容。

每个输入文档的

$startWith表达式值与connectToField匹配。

对于每个匹配的文档,connectFromField值将与集合中的connectToField值进行递归匹配。

集合

{ "_id" : 1, "cat_id" : 1, "title" : "Parent Category", "parent" : null }
{ "_id" : 2, "cat_id" : 2, "title" : "Child Category", "parent" : 1 }
{ "_id" : 3, "cat_id" : 3, "title" : "Sub Child Category", "parent" : 2 }

查询

Categories.aggregate([{
    $graphLookup: {
        from: "categories",
        startWith: "$cat_id",
        connectFromField: "cat_id",
        connectToField: "parent",
        as: "subCategory"
    }
}], callback)

输出

{
    "_id": 1,
    "cat_id": 1,
    "title": "Parent Category",
    "parent": null,
    "subCategory": [{
        "_id": 3,
        "cat_id": 3,
        "title": "Sub Child Category",
        "parent": 2
    }, {
        "_id": 2,
        "cat_id": 2,
        "title": "Child Category",
        "parent": 1
    }]
} {
    "_id": 2,
    "cat_id": 2,
    "title": "Child Category",
    "parent": 1,
    "subCategory": [{
        "_id": 3,
        "cat_id": 3,
        "title": "Sub Child Category",
        "parent": 2
    }]
} {
    "_id": 3,
    "cat_id": 3,
    "title": "Sub Child Category",
    "parent": 2,
    "subCategory": []
}