【问题标题】:mongo aggregate how to choose ‘$graphLookup or $lookup’mongo 聚合如何选择“$graphLookup 或 $lookup”
【发布时间】:2019-03-09 17:48:15
【问题描述】:

我不知道如何选择'$graphLookup or $lookup' 其他类似

期待mongodb官方更完整的文档

示例:

{parentId: 0, cid: 1, other: 'a'},
{parentId: 0, cid: 2, other: 'b'},
{parentId: 0, cid: 3, other: 'c'},

{parentId: 1, cid: 11, other: 'aa'},
{parentId: 2, cid: 12, other: 'ab'},
{parentId: 3, cid: 13, other: 'ac'},

结果:

{
parentId: 0, cid: 1, other: 'a', 
  children: [
   {parentId: 1, cid: 11, other: 'aa'},
  ]
},{
parentId: 0, cid: 2, other: 'b',
  children: [
   {parentId: 2, cid: 12, other: 'ab'},
  ]
},{
parentId: 0, cid: 3, other: 'c',
  children: [
   {parentId: 3, cid: 13, other: 'ac'},
  ]
}
},

怎么办?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    你需要使用$graphLookup

    db.collection.aggregate([
      {
        $match: {
          "parentId": {
            $eq: 0
          }
        }
      },
      {
        $graphLookup: {
          from: "collection",
          startWith: "$cid",
          connectFromField: "cid",
          connectToField: "parentId",
          as: "children"
        }
      }
    ])
    

    $lookup 用于“加入”集合进行处理。

    【讨论】:

    • 你这样做的结果是``` children: [] ``` 谢谢你的回答
    猜你喜欢
    • 2021-03-27
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 2022-01-05
    • 2021-06-04
    • 1970-01-01
    • 2020-04-09
    • 2021-05-26
    相关资源
    最近更新 更多