【问题标题】:convert a $lookup result to an object instead of array将 $lookup 结果转换为对象而不是数组
【发布时间】:2022-01-29 02:44:21
【问题描述】:

我正在从 _id 进行 $lookup。所以结果总是 1 个文档。因此,我希望结果是一个对象,而不是一个包含一项的数组。

let query = mongoose.model('Discipline').aggregate([
    {
      $match: {
        project: mongoose.Types.ObjectId(req.params.projectId)
      },
    },
    {
      $lookup: {
        from: "typecategories",
        localField: "typeCategory",
        foreignField: "_id",
        as: "typeCategory"
      }
    },
    {
      $project: {
        title: 1, typeCategory: "$typeCategory[0]"
      }
    }
  ]);

这个符号:"$typeCategory[0]" 不起作用。有什么聪明的方法吗?

【问题讨论】:

标签: javascript node.js mongodb mongoose


【解决方案1】:

您可以使用$unwind。它从输入文档中解构一个数组字段,为每个元素输出一个文档

let query = mongoose.model('Discipline').aggregate([
    {
      $match: {
        project: mongoose.Types.ObjectId(req.params.projectId)
      },
    },
    {
      $lookup: {
        from: "typecategories",
        localField: "typeCategory",
        foreignField: "_id",
        as: "typeCategory"
      }
    },
    {$unwind: '$typeCategory'},
    {
      $project: {
        title: 1, typeCategory: "$typeCategory"
      }
    }
  ]);

【讨论】:

  • 只是在这里指出 $unwind 中使用的 $typeCategory 是这里返回的名称(如:“typeCategory”),而不是 localField 的名称。
【解决方案2】:

您可以在$project 阶段使用$arrayElemAt

$arrayElemAt 的语法是{ $arrayElemAt: [ <array>, <idxexOfArray> ] }

喜欢:

mongoose.model('Discipline').aggregate([
   {
      $match: {
        project: mongoose.Types.ObjectId(req.params.projectId)
      },
   },
   {
      $lookup: {
        from: "typecategories",
        localField: "typeCategory",
        foreignField: "_id",
        as: "typeCategory"
      }
   },
   {
      $project: {
         name: 1, typeCategory: {$arrayElemAt:["$typeCategory",0]}
      }
   }
]);

【讨论】:

  • 请注意,此语法仅在您不排除投影中的属性时才有效。在您的示例中,如果 name 设置为 0,您将收到 BadProjection 错误
【解决方案3】:

使用$first返回数组的第一个元素:

$project: {
    title: 1, 
    typeCategory: {$first: "$typeCategory"}
}

【讨论】:

    【解决方案4】:

    合并两个集合:

    {$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$typeCategory", 0 ] }, "$$ROOT" ] } }    }, 
    
    { $project: { typeCategory: 0 } }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      • 2011-04-13
      相关资源
      最近更新 更多