The Foreign field of $lookup could be the field of

2019-07-14 00:03发布

问题:

$lookup is used to perform a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing in 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>
     }
}

Could the foreignField be the field of the nested document of from collection?

For example, there are two collections as following.

history collection

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

childsgroup collection

[{
  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'}
  }]
}]

so, this aggregation code could be executed like this?

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

So I want to get the result like this.

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

Isn't this possible?

回答1:

There's no positional operator for $lookup but you can use custom pipeline in MongoDB 3.6 to define custom join 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"
        }
    }
])

First $match added to improve performance: we want to find only those documents from childsgroup that contain matching child_id and then we can match subdocuments after $unwind stage.