Mongoose split documents to 2 groups with counters

Viewed 42

I have a model of the following schema:

const mongoose = require('mongoose');

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

const LivenessLog = mongoose.model('LivenessLog', livenessLogSchema);

module.exports = LivenessLog;

I want to split all documents to 2 groups: those whose probability value is less than 0.001 and those whose value is greater than 0.001. Also, in each group, I want to count for each probabilty value - how many documents has the same value.

So basically if I had the following probabilities data: [0.00001, 0.000003, 0.000025, 0.000003, 0.9, 0.6, 0.6], I'd like to get as a result: { less: { 0.00001: 1, 0.000003: 2, 0.000025:1 }, greater: { 0.9: 1, 0.6: 2 }.

This is my current aggregate method:

const livenessProbilitiesData = await LivenessLog.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: {
        }
    }
]);

Note that I use undeclared variables startDate, endDate. These are input I get to filter out unrelevant documents (by timestamp).

0 Answers
Related