在mongodb中选择具有左外连接的特定字段

时间:2018-02-03 07:24:04

标签: mongodb

如何从左集合中选择特定字段以及左外连接到某个集合

  db.users.aggregate(
{

$lookup:
    {
        from: 'vehicles',
        localField: "_id",
        foreignField: "vehicleBelongsTo",
        as: "mapping"
     }
 }
 )

在此查询中,我还获取密码字段如何排除它或如何从用户集合中选择特定字段

1 个答案:

答案 0 :(得分:2)

您可以使用$Project运算符和Project所需的所有字段,如下所示:

     db.users.aggregate([
  {
    $lookup: {
      from: "vehicles",
      localField: "_id",
      foreignField: "vehicleBelongsTo",
      as: "mapping"
    }
  },
  {
    $project: { 
        name:1,
        email:1,
        // dont include password here
        //list all fields u need here
       //now Probably show only "vehicles_name" from mapping.
        "mapping.vehicles_name":1 //if need full mapping then mapping:1
    }
  }
]);