将$lookup查询结果转换为对象而不是数组

49

我正在从 _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]" 没有起作用。有没有更聪明的方法?


1
现在先使用 typeCategory:{$arrayElemAt: ["$typeCategory", 0 ]}。有一个特定的问题需要解决,可以查看这个链接 https://jira.mongodb.org/browse/SERVER-27589。 - s7vr
@s7vr提到的链接已被关闭,因为是重复问题。这是未解决的问题。https://jira.mongodb.org/browse/SERVER-22384 - Adarsh Madrecha
4个回答

101
您可以直接使用$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的名称。 - Karanveer Singh

8

您可以在$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]}
      }
   }
]);

请注意,此语法仅在投影中不排除属性时才起作用。在您的示例中,如果名称设置为0,则会出现BadProjection错误。 - thomaux

3

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

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

1

合并两个集合:

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

{ $project: { typeCategory: 0 } }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接