【问题标题】:MongoDb $lookup nested document in array fieldsMongoDb $lookup 数组字段中的嵌套文档
【发布时间】:2021-12-30 07:04:47
【问题描述】:

我有一个文档类别列表:documentCategory 我有一个文档表
如何将 Document 中的单个文档放入 documentCategory 中的 UI 子项中


1、I have a list of document categories : documentCategory

{
    "_id" : ObjectId("61cd249f50f3abf2e172d743"),
    "name" : "Vue3",
    "pid" : "-1",
    "level" : 1,
    "children" : [ 
        {
            "name" : "UI",
            "pid" : "61cd249f50f3abf2e172d743",
            "level" : 2,
            "_id" : ObjectId("61cd27d1f3b969fec5458d89")
        }
    ]
}


2、I have a document table  
{
    "_id" : ObjectId("61cd4813db3e3db388e1d7cf"),
    "name" : "ElementUI",
    "cid" : "61cd27d1f3b969fec5458d89",
    "cname" : "UI",
    "pid" : "61cd249f50f3abf2e172d743",
    "pname" : "Vue3",
}

希望得到结果:


{
    "_id" : ObjectId("61cd249f50f3abf2e172d743"),
    "name" : "Vue3",
    "pid" : "-1",
    "level" : 1,
    "children" : [ 
        {
            "name" : "UI",
            "pid" : "61cd249f50f3abf2e172d743",
            "_id" : ObjectId("61cd27d1f3b969fec5458d89"),  
            children:[
                {name:'ElementUI'},{name:'**'}
            ]
        }
    ]
}

如何将 Document 中的单个文档放入 documentCategory 中的 UI 子项中

【问题讨论】:

  • 您似乎想将category _idcid 表匹配,对吗?从ObjectId 向上查找String 会导致问题。或者您是否想查找pid 是否相同

标签: mongodb mongoose mongodb-query aggregate lookup


【解决方案1】:

由于您尝试将 ObjectId 匹配到字符串上,因此我必须添加 $set 阶段以将它们转换为相同的类型(字符串)。

请注意,我命名了我的第二个集合表而不是表,因为最佳实践是复数

db.collection.aggregate([
  {
    '$match': {
      'name': 'Vue3'
    }
  }, {
    '$unwind': {
      'path': '$children'
    }
  }, {
    '$set': {
      'children._id': {
        '$toString': '$children._id'
      }
    }
  }, {
    '$lookup': {
      'from': 'tables', 
      'localField': 'children._id', 
      'foreignField': 'cid', 
      'as': 'children.children', 
      'pipeline': [
        {
          '$project': {
            'name': 1, 
            '_id': 0
          }
        }
      ]
    }
  }, {
    '$group': {
      '_id': '$_id', 
      'name': {
        '$first': '$name'
      }, 
      'pid': {
        '$first': '$pid'
      }, 
      'level': {
        '$first': '$level'
      }, 
      'children': {
        '$push': '$children'
      }
    }
  }
])

【讨论】:

  • 谢谢你的回答,{ $addFields: { childId: { $toString: '$children._id' } } } 我试过addFields,这两种方法哪个更好?管道的作用是什么? ``` { $unwind: '$children' }, { $addFields: { childId: { $toString: '$children._id' } } }, { $lookup: { from: 'document', localField: 'childId' , foreignField: 'cid', as: 'children.children' } }, ```
  • 当我尝试使用 $project 过滤管道中的所有数据时,它似乎不起作用 $project: { name: 1, children: { name: 1, children: { _id: 1 ,名称:1,描述:1,链接:1,github:1,imgUrl:1,来源:1 } } }
猜你喜欢
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 2020-12-29
  • 2019-04-29
  • 2018-10-06
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
相关资源
最近更新 更多