【问题标题】:MongoDB Aggregate; Projecting min and max documentsMongoDB聚合;投影最小和最大文档
【发布时间】:2021-02-24 23:31:52
【问题描述】:
let pipeline = [
    {
        $group: {
            _id: "$user_id",
            minTime: { $min: "$time" },
            maxTime: { $max: "$time" }
        }
    }, 
    {
        $project: {
            // Looking to take the most recent document, and the
            // oldest document for a user and subtract their "weight"
            // attribute
        }
    }
]

我正在努力解决 MongoDB 聚合问题。我目前正在寻找最旧的文档,匹配“minTime”和时间匹配“maxTime”的最新文档,并减去它们的“权重”属性,基本上为用户获得净变化。我将如何将其投射到管道中? (时间也是一个unix时间戳)

【问题讨论】:

  • 如果您可以添加一些数据样本将会很有帮助,您使用的 $group 不是限制文档的东西,因此如果您的集合不是分片的,您可以执行 @987654323 @发布这个并在它的管道中使用时间来过滤它的价值。

标签: node.js mongodb express mongoose


【解决方案1】:
    let pipeline = [
    {
        $sort: {
            time: -1
        }
    },
    {
        $group: {
            _id: "$user_id",
            min: { $min: "$weight" },
            first: { $last: "$weight" }
        }
    },
    {
        $project: {
            total: {
                $subtract: [
                    "$min",
                    "$first"
                ]
            }
        }
    },
    {
        $group: {
            _id: null,
            users: { $sum: 1 },
            total: { $sum: "$total" }
        }
    }
]

这个管道解决方案最终在按时间戳排序后使用了 $first 和 $last 运算符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 2017-03-18
    相关资源
    最近更新 更多