1

I have an aggregation query for MongoDB 2.4 (we can't use another version :( ).

At one point I need the size or count of a set created in a group:

{
    $group: {
        _id: {
            type: '$type',
            week: '$week',
            day: '$day',
            year: '$year',
            hour: '$hour'
        },
        minutes: { 
            $addToSet: "$minutes"
        },
        sum_online: {
            $sum: "$online" 
        },
        sum_offline: {
            $sum: "$offline" 
        },
        sum_expired: {
            $sum: "$expired" 
        },
        min_date: {
            $min: "$date" 
        },
        max_date: { 
            $max: "$date" 
        }
    }
},
{
    $project: {
        day: "$_id.day",
        week: "$_id.week",
        year: "$_id.year",
        type: "$_id.type",
        hour: "$_id.hour",
        measurements: { $size: "$minutes" },
        sum_online: "$sum_online",
        sum_offline: "$sum_offline",
        sum_expired: "$sum_expired",
        min_date: "$min_date",
        max_date: "$max_date"
    }
},

It's about the "minutes". The result of the addToSet will be:

[
    0,
    10,
    20,
    30,
    40,
    50
]

Those are six items and I need the size of that set in my projection but version 2.4 has no $size function I can use. measurements: { $size: "$minutes" }, doesn't work. I get this error:

Thu Feb 18 12:50:03.214 aggregate failed: {
"errmsg" : "exception: invalid operator '$size'",
"code" : 15999,
"ok" : 0

Does anyone know of a way to get the size of that set?

Dion Snoeijen
  • 143
  • 2
  • 9
  • Yup. `$unwind` the resulting array and `{ "$sum": 1 }` on another group to get the count. MongoDB 2.4 is really a couple of years old now, and for young and evolving products like MongoDB, it's really not a great idea to hold onto older revisions like that. With a current 3.2.x release, the only backporting currently happening is into the 2.6.x series. So problems and lack of features in 2.4.x are going to stay that way. It's kind of like asking people to support Oracle 6 – Blakes Seven Feb 19 '16 at 02:14
  • Possible duplicate of [Querying internal array size in MongoDB](http://stackoverflow.com/questions/6722850/querying-internal-array-size-in-mongodb). Which means paying attention to all the older answers before `$size` was introduced. There are answers dating back to MongoDB 2.0.x at least. – Blakes Seven Feb 19 '16 at 02:17
  • Thank you! I will try to use the unwind. I know it's a bad idea to use such old version. We are stuck with an enterprise sla preventing flexibility. – Dion Snoeijen Feb 19 '16 at 13:48

0 Answers0