如何在Mongo中进行聚合时复制文档?

3
在Mongo中聚合时有没有办法复制文档呢?比如,我有一个类似于以下结构的“人”模式:

人:

{
  _id: ObjectId,
  fullName: string,
  matches: number
}

我希望创建一个聚合操作,它可以返回所有人的信息,并根据他们的 matches 数量,将每个人的文档重复。

例如,在这个集合中:

[{
  _id: 1,
  fullName: "John Doe",
  matches: 1
},
{
  _id: 2,
  fullName: "Bla Bla",
  matches: 2
}]

结果将是:
[{
  _id: 1,
  fullName: "John Doe",
  matches: 1
},
{
  _id: 2,
  fullName: "Bla Bla",
  matches: 2
},
{
  _id: 2,
  fullName: "Bla Bla",
  matches: 2
}]

我知道在聚合过程中可以添加文档字段,但没有找到关于添加文档的任何信息。


提供的答案中是否有您认为没有解决您的问题的内容?如果是,请在答案下评论以澄清需要解决的具体问题。如果它确实回答了您所提出的问题,请注意接受您所提出的问题的答案。 - turivishal
1个回答

2
  • $map 用于迭代循环范围,$range0 开始到 matches 数字结束,它将返回当前根文档的数组。
  • $unwind 解构 matches 数组。
  • $replaceRootmatches 对象替换为根对象。
db.collection.aggregate([
  {
    $project: {
      matches: {
        $map: {
          input: { $range: [0, "$matches"] },
          in: "$$ROOT"
        }
      }
    }
  },
  { $unwind: "$matches" },
  { $replaceRoot: { newRoot: "$matches" } }
])

Playground


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