获取同一集合中存在的3级分层数据

时间:2019-05-28 13:11:32

标签: mongodb

我有一个名为Skills的收藏集:

Skills:
 {  
       "_id":ObjectId("5cebbfbe09ce114302cd6028"),
       "name":"Java",
       "level":1.0,
       "status":"Approved",
       "parentId":"",
       "createDate":   ISODate("2019-05-27T10:45:18.904   Z"),
       "modifiedDate":   ISODate("2019-05-27T10:45:18.904   Z"),
       "createdBy":"Admin",
       "modifiedBy":"Admin"
    }/* 2 */{  
       "_id":ObjectId("5cebbfbe09ce114302cd6029"),
       "name":"Springs",
       "level":1.0,
       "status":"Approved",
       "parentId":ObjectId("5cebbfbe09ce114302cd6028"),
       "createDate":   ISODate("2019-05-27T10:45:18.904   Z"),
       "modifiedDate":   ISODate("2019-05-27T10:45:18.904   Z"),
       "createdBy":"Admin",
       "modifiedBy":"Admin"
    }/* 3 */{  
       "_id":ObjectId("5cebbfbe09ce114302cd602a"),
       "name":"Struts",
       "level":1.0,
       "status":"Approved",
       "parentId":ObjectId("5cebbfbe09ce114302cd6028"),
       "createDate":   ISODate("2019-05-27T10:45:18.904   Z"),
       "modifiedDate":   ISODate("2019-05-27T10:45:18.904   Z"),
       "createdBy":"Admin",
       "modifiedBy":"Admin"
    }/* 4 */{  
       "_id":ObjectId("5cebc0538a5ce6ceea9ce8f1"),
       "name":"MVC",
       "level":1.0,
       "status":"Approved",
       "parentId":ObjectId("5cebbfbe09ce114302cd602a"),
       "createDate":   ISODate("2019-05-27T10:47:47.684   Z"),
       "modifiedDate":   ISODate("2019-05-27T10:47:47.684   Z"),
       "createdBy":"Admin",
       "modifiedBy":"Admin"
    }

Java是Spring和Struts的父文档,而Struts是MVC的父文档。我想从同一集合中检索3级层次结构数据。或者,如果您对架构设计有任何建议,请也分享。我使用聚合框架进行了尝试,但未获得预期的输出。我使用了$lookup阶段。

db.skills.aggregate([  
   {  
      $project:{  
         name:1,
         level:1,
         status:1
      }
   },
   {  
      $lookup:{  
         from:"skills",
         localField:"_id",
         foreignField:"parentId",
         as:"Data"
      }
   }
]) 

我想要以这种方式输出:

"_id":ObjectId("5cebbfbe09ce114302cd6028"),
"name":"Java",
"level":1.0,
"status":"Approved",
Data:[  
   {  
      "_id":ObjectId("5cebbfbe09ce114302cd6029"),
      "name":"Springs",
      "level":1.0,
      "status":"Approved"
   },
   {  
      "_id":ObjectId("5cebbfbe09ce114302cd602a"),
      "name":"Struts",
      "level":1.0,
      "status":"Approved",
      Data:[  
         {  
            "_id":ObjectId("5cebc0538a5ce6ceea9ce8f1"),
            "name":"MVC",
            "level":1.0,
            "status":"Approved"
         }
      ]``
   }
]

0 个答案:

没有答案