代码之家  ›  专栏  ›  技术社区  ›  Andrew Li

$lookup的外部字段可能是嵌套文档的字段?

  •  1
  • Andrew Li  · 技术社区  · 7 年前

    $lookup 用于对同一数据库中未共享的集合执行左外部联接,以从联接的集合中筛选文档,以便在Mongo中进行处理。

    {
       $lookup:
         {
           from: <collection to join>,
           localField: <field from the input documents>,
           foreignField: <field from the documents of the "from" collection>,
           as: <output array field>
         }
    }
    

    会不会 foreignField 是的嵌套文档的字段 from 收藏?

    例如,有两个集合,如下所示。

    history

     [{
      id:'001',
      history:'today worked',
      child_id:'ch001'
    },{
      id:'002',
      history:'working',
      child_id:'ch004'
    },{
      id:'003',
      history:'now working'
      child_id:'ch009'
    }],
    

    childsgroup 收集

    [{
      groupid:'g001', name:'group1'
      childs:[{
          id:'ch001',
          info:{name:'a'}
      },{
          id:'ch002',
          info:{name:'a'}
      }]
    },{
      groupid:'g002', name:'group1'
      childs:[{
          id:'ch004',
          info:{name:'a'}
      },{
          id:'ch009',
          info:{name:'a'}
      }]
    }]
    

    所以,这个 aggregation

    db.history.aggregate([
       {
         $lookup:
           {
             from: "childsgroup",
             localField: "child_id",
             foreignField: "childs.$.id",
             as: "childinfo"
           }
      }
    ])
    

         [{
          id:'001',
          history:'today worked',
          child_id:'ch001',
          childinfo:{
              id:'001',
              history:'today worked',
              child_id:'ch001'
           }
        },  .... ]
    

    这不可能吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   mickl    7 年前

    $lookup没有位置运算符,但可以使用自定义 pipeline 在MongoDB 3.6中定义自定义联接 conditions

    db.history.aggregate([
        {
            $lookup: {
                from: "childsgroup",
                let: { child_id: "$child_id" },
                pipeline: [
                    { $match: { $expr: { $in: [ "$$child_id", "$childs.id" ] } } },
                    { $unwind: "$childs" },
                    { $match: { $expr: { $eq: [ "$childs.id", "$$child_id" ] } } },
                    { $replaceRoot: { newRoot: "$childs" } }
                ],
                as: "childInfo"
            }
        }
    ])
    

    弗斯特 $match 添加以提高性能:我们只希望从 childsgroup child_id 然后我们可以在之后匹配子文档 $unwind

    推荐文章