【问题标题】:Mongoose How To Query Within Date Range And Extract Highest Values For Each Day?Mongoose如何在日期范围内查询并提取每天的最大值?
【发布时间】:2014-03-11 11:32:06
【问题描述】:

如何使用 mongoose/mongodb 设计查询以在日期范围内搜索并提取该范围内每一天的最高价格值?现在,我知道如何做到这一点的唯一方法是在日期范围内执行查询,然后处理结果以获取每天的最高价格。但这似乎是一种常见的需求,所以我想知道是否可以在查询中完成所有操作:

这是我的模型,它提供了一些可以在查询中使用的不同内容。 date 属性是 Date 类型,day 属性是字符串类型。 day 属性采用这种格式 day: "02/11/2014"。 price 属性是 Number 数据类型,格式如下:price: 114.61

// Price Schema
var PriceSchema = new Schema({
    full_date: {
        type: String,
        required: true,
        unique: true,
        trim: true
    },
    day: {
        type: String,
        required: true,
        trim: true
    },
    price: {
        type: Number,
        required: true,
        trim: true
    },
    date: {
        type: Date,
        unique: true,
        required: true
    }
});

这是一个日期范围内的查询,但我可以做类似于 forEach 日期返回最高价格的事情吗?

Price.find({ date: { $lt: end, $gt: start }}, function(err, prices) {
            if (err) {
                console.log(err);
            } else {
                res.jsonp(poolprices);
            }
        });

【问题讨论】:

  • 答案中是否有没有解决您的问题的内容?

标签: javascript node.js mongodb mongoose aggregation-framework


【解决方案1】:

您可能希望为此使用aggregation pipeline:

Price.aggregate([
    // Match the date range
    { "$match": { "date": { "$lt": end, "$gt": start} } },

    // Change document with date to a value just for the day
    { "$project":{ 
        "date": {
           "year": { "$year": "$date"}, 
           "month": { "$month": "$date" }, 
           "day": { "$dayOfMonth": "$date"}
        },
        "price": 1
    }},

    // Sort everything (descending so highest price per day is on top)
    { "$sort": { "date.year": -1, "date.month": -1, "date.day": -1, "price": -1 }},

    // Group per day (now as a nice string), and keep the first price (highest)
    { "$group": { 
        "_id": {
            "$concat": [{ "$substr": ["$date.year", 0, 4] },
            "-",
           { "$substr": ["$date.month", 0, 2]},
            "-", 
           { "$substr": ["$date.day", 0, 2]}]
        },
        "price": { "$first": "$price"}
    }},

    // Make field names nicer
    { "$project": { "_id":0, "day": "$_id", "price": 1 } }

],
function(err,result) {
    //process here
})

因此结果在您的范围内每天只有 1 个价格,无需以编程方式循环结果。

这是一个不错的小操作,它利用Date Operators 分解日期字段,然后利用$substr 和$concat 为您的结果返回更好的值。考虑到您现在知道在这里可以做什么,您可能还会重新考虑架构中的一些字段。

【讨论】:

    猜你喜欢
    • 2021-01-02
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 2015-12-03
    • 1970-01-01
    • 2016-02-15
    • 2020-07-29
    相关资源
    最近更新 更多