node.js - 猫鼬计数文件大于和小于特定值
问题描述
我有以下模式的模型:
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
。这些是我用来过滤不相关文档(按时间戳)的输入。
解决方案
自己解决了:
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,
};
推荐阅读
- sql - SQL Not Like 语句在条件语句中不起作用
- python - 如何使用 Win32Com 处理 Inkscape?
- html - 位置置顶不生效
- apache-kafka - 为什么我的 NiFi PublishKafka 处理器仅适用于以前的版本?
- mysql - 怎么换一个字
- tensorflow - TensorFlow 多项式回归 Nan 中的参数
- java - Gradle:使用依赖库创建不可执行的 jar 和可执行的 shell 脚本作为包分发
- r - R, sf: 与多边形的边界相交线,提取这些交点的坐标
- javascript - React with Hooks:什么时候重新渲染?
- c# - 类中可能存在空接口对象的最佳实践