在mongodb中填充数组

时间:2018-12-07 06:50:10

标签: mongodb

我有如下数组:

"developers" : [ 
        "5bfe4059c8698b30183db389", 
        "5bfe406ec8698b30183db38a"
    ]

其模型如下所示:

developers:{
    type: Array,
    ref: 'User',
    default:[]
  }

我想在mongodb中填充它。我尝试了.populate('developers')但没有运气。

1 个答案:

答案 0 :(得分:0)

您可以使用聚合

首先,您必须展开数组

{
  $unwind:
    {
      path: <field path>,
      preserveNullAndEmptyArrays: <boolean>
    }
}

输入文字后,您可以使用$ loockup

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

整个管道看起来像

db.getCollection('dates').aggregate([{
$unwind:'$developers'
},{
 $lookup:
         {
           from: 'users',
           localField: 'developers',
           foreignField:'id',
           as: 'info'
         }
}])

希望这会有所帮助