在mongodb中,unwind正在做什么修复?

时间:2016-09-22 15:36:31

标签: arrays node.js mongodb

  

注意:我已经通过在我的电脑上执行代码添加了屏幕截图。我已经多次看过这个,但我至少无法向自己解释这个问题

this MongoDB $unwind for nodejs 11:10 分钟教程中 - 发言人说:

  

此查询:


db.companies.aggregate([
    { $match: {"funding_rounds.investments.financial_org.permalink": "greylock" } },
    { $project: {
        _id: 0,
        name: 1,
        amount: "$funding_rounds.raised_amount",
        year: "$funding_rounds.funded_year"
    } }
])

生成包含金额和年份数组的文档。

documents that have arrays for both amount and year

  

因为我们正在为资金回合阵列中的每个元素访问筹集的金额和资助年度。 要解决此问题,我们可以在此聚合管道中的项目阶段之前包含一个展开阶段,并通过说我们想要unwind资金回合数组来对其进行参数化:


db.companies.aggregate([
    { $match: {"funding_rounds.investments.financial_org.permalink": "greylock" } },
    { $unwind: "$funding_rounds" },
    { $project: {
        _id: 0,
        name: 1,
        amount: "$funding_rounds.raised_amount",
        year: "$funding_rounds.funded_year"
    } }
])

unwind has the effect of outputting to the next stage more documents than it receives as input

  

unwind具有输出更多文档而不是输入的文档的效果。

我的困惑:

  • 发言者在 1:21 分钟时指的是什么问题?
  • 他指的是什么修复

1 个答案:

答案 0 :(得分:0)

问题是我们需要为每组[公司,金额,年份]提供单个文档,其中金额和年份都只是一个标量值。我们拥有的输入有数组,$ unwind将这些数据转换为单个值,如讲座中所述。

讲座并没有给出一个特定的问题,这个问题试图解决,但是我建议它会是这样的:"给我一份报告,说明Greylock每年投入多少资金。然后每年给我一份报告,显示公司的资金情况,按照提供的金额排序。"如果您考虑如何使用聚合框架生成数据,您可以看到这些报告需要一组文档,如讲座中所示。