【问题标题】:MongoDB lookup and unwindMongoDB 查找和展开
【发布时间】:2022-02-13 06:09:41
【问题描述】:

我正在尝试进行查找,该查找工作正常,并且在正确的文档中作为“指标”。查找文档在其对象内部有一个名为“历史”的数组。我正在尝试展开该历史记录并对其执行一个方面,即我直接在查找集合上运行的聚合查询。

但是,在这里使用它时,它不会返回任何东西。我是否错误地展开了这个?应该是$metrics.history 吗?

{
  from: 'historicprices',
  localField: 'collectibleId',
  foreignField: 'collectibleId',
  pipeline: [
    {$set: {"target-date": "$$NOW"}}, 
    {$unwind: {path: "$history"}}, 
    {$facet: {
        "one_day": [
            { $match: { $expr: { $lte: [{$subtract: ["$target-date", "$history.date" ]}, {$multiply: [24,60,60,1000] }] } } },
            { $group: { _id: null, "first": { $first: "$history.value" }, "last": { $last: "$history.value" }, "min-price": {"$min": "$history.value"}, "max-price": {"$max": "$history.value"} } },
            { $unset: ["_id"]}
        ]
        "one_week": [
             { $match: { $expr: { $lte: [{$subtract: ["$target-date", "$history.date" ]}, {$multiply: [7, 24, 60, 60, 1000] }] } } },
             { $group: { _id: null, "min-price": {"$min": "$history.value"}, "first": { $first: "$history.value" }, "last": { $last: "$history.value" }, "max-price": {"$max": "$history.value"} } },
             { $unset: ["_id"]}
        ]
    }}
  ],
  as: 'metrics',
}

谢谢

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:

    也许您需要将preserveNullAndEmptyArrays: true 添加到您的放松阶段。否则,如果其中一个文档没有返回此字段,则不会收到任何数据。

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 2017-09-10
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多