首页 > 解决方案 > 猫鼬计数文件大于和小于特定值

问题描述

我有以下模式的模型:

const mongoose = require('mongoose');

const logSchema = new mongoose.Schema({
    probability: {
        type: Number,
        required: false,
    },
    timestamp: {
        type: Date,
        required: true,
    }
}, {
    timestamps: true
});

const Log = mongoose.model('Log', logSchema);

module.exports = Log;

我想将所有文档分成 2 组:probability值小于0.001的那些和值大于的那些0.001。此外,在每个组中,我想计算每个probabilty值 - 有多少文档具有相同的值。

所以基本上如果我有以下概率数据:[0.00001, 0.000003, 0.000025, 0.000003, 0.9, 0.6, 0.6],我想得到结果:{ less: { 0.00001: 1, 0.000003: 2, 0.000025:1 }, greater: { 0.9: 1, 0.6: 2 }

这是我目前的aggregate方法:

const livenessProbilitiesData = await Log.aggregate([
    {
        $match: {
            timestamp: {
                $gte: moment(new Date(startDate)).tz('Asia/Jerusalem').startOf('day').toDate(),
                $lte: moment(new Date(endDate)).tz('Asia/Jerusalem').endOf('day').toDate(),
            }
        }
    },
    {
        $group: {
        }
    }
]);

请注意,我使用未声明的变量startDate, endDate。这些是我用来过滤不相关文档(按时间戳)的输入。

标签: node.jsmongoose

解决方案


自己解决了:

const livenessProbilitiesData = await LivenessLog.aggregate([
    {
        $match: {
            eventName: 'probability',
            timestamp: {
                $gte: moment(new Date(startDate)).tz('Asia/Jerusalem').startOf('day').toDate(),
                $lte: moment(new Date(endDate)).tz('Asia/Jerusalem').endOf('day').toDate(),
            }
        },
    },
    {
        $group: {
            _id: { $trunc: [ '$probability', 4 ] },
            count: { $sum: 1 },
        },
    },
    {
        $sort: { _id: 1 },
    },
    {
        $project: {
            _id: 0,
            less: { $lt: ['$_id', 0.001] },
            x: '$_id',
            y: '$count',
        },
    },
    {
        $group: {
            _id: '$less',
            probabilities: { $push: { x: '$x', y: '$y' } },
        },
    },
    {
        $project: {
            _id: 0,
            probabilities: 1,
        },
    }
]);

if (livenessProbilitiesData.length === 0) {
    return {
        less: [],
        greater: [],
    }
}

return {
    less: livenessProbilitiesData[0].probabilities,
    greater: livenessProbilitiesData[1].probabilities,
};

推荐阅读