首页 文章

MongoDB聚合 - $ project中的动态字段路径

提问于
浏览
1

我试图将聚合 $project 阶段中的新字段的值设置为等于依赖于另一个变量的字段路径(不同日期的不同股票价格) .

我可以使用 getPrice 全局帮助程序调用此字段路径以在模板中使用,但是我找不到允许我从聚合中的许多字段路径中进行选择的任何MongoDB管道运算符(我看到 $cond ,它只允许两个选项) . 我还看到了如何计算新字段的值,但我的用例不需要任何计算,该值已存在于文档中 .

这个Meteorpad显示了我更清楚的问题,但最相关的代码如下 . 我可以在$ project中将 dynamicPrice 的值设置为什么?谢谢 .

//Document being aggregated
{
  ticker: "AAPL",
  eps: "9.20",
  lastPrice: "119.03",
  closingPrices: [
    {date: "2015-12-03", close: "115.20"},
    {date: "2015-12-04", close: "119.03"}
  ]
}

//Function to find price for selected date, in /common.js, works for templates
    getPrice = function(companyId) {
        var company = Companies.findOne({_id:companyId});
        var valuation = Template.parentData(1);
        var valuationDate = valuation.valuationDate;
        var valuationPrice = 0;
        _.each(company.closingPrices, function(closingPrices) {
            if (closingPrices.date == valuationDate) valuationPrice = closingPrices.close;
        });
        return valuationPrice;
    };

//$project stage of aggregation
           {
              $project: {
                _id: 1,
                eps: 1,
                lastPrice: 1,
                dynamicPrice: getPrice
              }
            }

[编辑:缩小文字以简化问题]

1 回答

  • 0

    我能够使用 $unwind 来解决这个问题 . 全局帮助程序 getPrice 实际上与聚合无关 . 在这里更新了Meteorpad .

    //Documents being aggregated
    {
      ticker: "AAPL",
      eps: "9.20",
      lastPrice: "119.03",
      closingPrices: [
        {date: "2015-12-03", close: "115.20"},
        {date: "2015-12-04", close: "119.03"}
      ]
    },
    //...more documents
    
    //Aggregation
    var valuation = Valuations.findOne({_id: valuationId});
    var valuationDate = valuation.valuationDate;
    
    var pipeline = [
            {
              $unwind: "$closingPrices"
            },
            {
              $match: {
                "closingPrices.date": valuationDate
              }
            },
            {
              $project: {
                _id: 1,
                eps: 1,
                lastPrice: 1,
                dynamicPrice: "$closingPrices.close"
              }
            }
            //...$group stage with calculations
    

相关问题