在MongoDB中管理多级类别

时间:2019-05-11 15:16:00

标签: node.js mongodb

我正在用nodejs制作项目,我想在MongoDB中管理多级类别。

数据以以下格式保存在MongoDB中,其中类别是使用父级映射的,一个类别可以是2个父级

([
  {
    "parent": [],
    "name": "Things",
    "level": 1,
    "slug": "things"
  },
  {
    "parent": [
      "things"
    ],
    "name": "Living Things",
    "level": 2,
    "slug": "living-things"
  },
  {
    "parent": [
      "living-things"
    ],
    "name": "Plants",
    "level": 3,
    "slug": "plants"
  },
  {
    "parent": [
      "living-things"
    ],
    "name": "Animals",
    "level": 3,
    "slug": "animals"
  },
  {
    "parent": [
      "animals",
      "living-things"
    ],
    "name": "Mammals",
    "level": 4,
    "slug": "mammals"
  }
]
)

// Requires official MongoShell 3.6+
use blogs-builder;
db.getCollection("cat").aggregate(
    [
  {
    "$project": {
      "_id": NumberInt(0),
      "c1": "$$ROOT"
    }
  },
  {
    "$lookup": {
      "localField": "c1.slug",
      "from": "cat",
      "foreignField": "parent",
      "as": "c2"
    }
  },
  {
    "$unwind": {
      "path": "$c2",
      "preserveNullAndEmptyArrays": true
    }
  },
  {
    "$lookup": {
      "localField": "c2.slug",
      "from": "cat",
      "foreignField": "parent",
      "as": "c3"
    }
  },
  {
    "$unwind": {
      "path": "$c3",
      "preserveNullAndEmptyArrays": true
    }
  },
  {
    "$match": {
      "c1.parent": "things"
    }
  },
  {
    "$project": {
      "c1.parent": "$c1.parent",
      "c1.slug": "$c1.slug",
      "c2.parent": "$c2.parent",
      "c2.slug": "$c2.slug",
      "c3.parent": "$c3.parent",
      "c3.slug": "$c3.slug",
      "_id": NumberInt(0)
    }
  }
],
{
  "allowDiskUse": true
}
);

以下是预期结果:

    [
  {
    id : '012215',
    name : 'Things',
    slug : 'things',
    child : 
    [
      {
        id : '155546',
        name : 'Living Things',
        slug : 'living-things',
        child : 
        [
          {
            id : '15165485',
            name : 'Plants',
            slug : 'plants',
            child : []
          },
          {
            id : '15165485',
            name : 'Mammals',
            slug : 'mammals',
            child : []
          },
          {
            id : '125485121',
            name : 'Animals',
            slug : 'animals',
            child : 
            [
              {
                id : '15165485',
                name : 'Mammals',
                slug : 'mammals',
                child : []
              }
            ]
          }
        ]
      }
    ]
  },
]

我是MongoDb的新手,非常感谢您的帮助。提前致谢。干杯!!!

0 个答案:

没有答案