如何使用MongoDb聚合框架计算每日记录

时间:2020-06-14 12:16:44

标签: mongodb mongoose aggregation-framework

我有一个日志收集,旨在提供每日记录的统计信息

[
    {
        "_id": "5ee4f58be451502a40fb2a83",
        "name": "Cement",
        "description": "Construction",
        "price": 1400,
        "quantity": 30,
        "quantitySold": -5,
        "itemDestination": "Trocadero",
        "createdAt": "2020-06-13T15:49:32.684Z",
        "updatedAt": "2020-06-13T15:49:32.684Z",
        "__v": 0
    },
    {
        "_id": "5eddea221bab5221e4ee2238",
        "name": "Pop",
        "description": "Construction",
        "price": 500,
        "quantity": 19,
        "quantitySold": -5,
        "itemDestination": "Amore",
        "createdAt": "2020-06-08T07:34:58.569Z",
        "updatedAt": "2020-06-08T07:34:58.569Z",
        "__v": 0
    },
    {
        "_id": "5edde9f51bab5221e4ee2237",
        "name": "Pop",
        "description": "Construction",
        "price": 500,
        "quantity": 24,
        "quantitySold": -6,
        "itemDestination": "Trocadero",
        "createdAt": "2020-06-08T07:34:13.700Z",
        "updatedAt": "2020-06-08T07:34:13.700Z",
        "__v": 0
    }
]

我想获取totalQuantitySold的每日记录和numberSold的每日平均值。但是只能执行以下操作

//logcontroller.js


    Log.aggregate([

        {
            $group:
              {
                _id: "$name",
                totalAmountSold:{$sum:"$quantitySold" },
                avgQuantitySold: { $avg: "$quantitySold" },


              }
          },
    ])

输出:

{
    "results": [
        {
            "_id": "Cement",
            "totalQuantitySold": -5,
            "avgQuantitySold": -5
        },
        {
            "_id": "Pop",
            "totalQuantitySold": -11,
            "avgQuantitySold": -5.5
        }
    ]
}

但是,我面临着根据每日条目提取这些统计信息的挑战...如果有人可以提供帮助,我将不胜感激。这是我的日志架构:

    {
        // _id: mongoose.Schema.Types.ObjectId,
        name: { type: String, required: true },
        description: { type: String, required: true },
        price: { type: Number, required: true },
        quantity: { type: Number, required: true },
        quantitySold: { type: Number, required: true },
        supplier: String,
        taxable: Boolean,
        itemDest: String,

    },
    { timestamps: true }
);

// Create model from the schema
const Log = mongoose.model('Log', LogSchema);

// Export model
module.exports = Log;

1 个答案:

答案 0 :(得分:0)

您需要在分组密钥中包括日期。由于您将ISODate存储为createdAt / updatedAt,因此可以使用$dateToString将日期+转换为Y-m-d格式:

Log.aggregate([
    {
        $group: {
            _id: { name: "$name", day: { $dateToString: { format: "%Y-%m-%d", date: "$updatedAt" } } },
            totalAmountSold:{$sum:"$quantitySold" },
            avgQuantitySold: { $avg: "$quantitySold" }
        }
    },
])

如果您只需要按日期过滤,也可以从name中删除_id部分。

Mongo Playground