Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to type cast data inside an aggregation pipeline on MongoDB?

When I need to aggregate things by date using the aggregate command on MongoDB, I usually do this:

 db.mycollection.aggregate(
 {
        $project: {
            day: {$dayOfMonth: "$date"},
            mon: {$month: "$date"},
            year: {$year: "$date"},
        }
    },
    {
        $group: {
            _id : {day: "$day", mon: "$mon", year: "$year"},
            count: {$sum: 1}
        }
    }
 )

and eventually concatenate the day, mon, and year fields into a date string in the application. For many reasons though, sometimes I want to concatenate the fields before leaving the database, so I initially tried:

 db.mycollection.aggregate(
 {
        $project: {
            day: {$dayOfMonth: "$date"},
            mon: {$month: "$date"},
            year: {$year: "$date"},
        }
    },
    $project: {
            datestr: {
                $concat : ["$year", "-", "$month", "-", "$day"]
            }
        }
    },

    {
        $group: {
            _id : {day: "$day", mon: "$mon", year: "$year"},
            count: {$sum: 1}
        }
    }
 )

This won't work because $concat expects strings and day, mon and year are integers. So, my question is: can I type cast a field with the $project operation?

like image 492
Rafael S. Calsaverini Avatar asked Feb 11 '14 12:02

Rafael S. Calsaverini


People also ask

What passes through a MongoDB aggregation pipeline?

An aggregation pipeline consists of one or more stages that process documents: Each stage performs an operation on the input documents. For example, a stage can filter documents, group documents, and calculate values. The documents that are output from a stage are passed to the next stage.

Can we use populate in aggregate MongoDB?

Short answer: You can't.

When might you use $let in an aggregation pipeline?

$let can access variables defined outside its expression block, including system variables. If you modify the values of externally defined variables in the vars block, the new values take effect only in the in expression. Outside of the in expression, the variables retain their previous values.

Which aggregation method is preferred for use by MongoDB?

The pipeline provides efficient data aggregation using native operations within MongoDB, and is the preferred method for data aggregation in MongoDB. The aggregation pipeline can operate on a sharded collection.


1 Answers

Yes, you can use $substr for casting a number to a string. Your missing link would look like:

{
    $project: {
        day_s:  { $substr: [ "$day",   0, 2 ] }, 
        mon_s:  { $substr: [ "$month", 0, 2 ] }, 
        year_s: { $substr: [ "$year",  0, 4 ] }
    }
}
like image 123
heinob Avatar answered Oct 05 '22 17:10

heinob