mongoid group by query



stages =  [
   { "$match" => { column_name: "Value" } },
   { "$group" => {  
             "_id" => { 
                  "name_of_your_choice"=>"$column_name",
                  "year" => { "$year" => "$column_name" },
                  "month" => { "$month" => "$column_name" },
                  "day" => { "$dayOfMonth" => "$column_name" },
                  "hour"=> {"$hour" => "$column_name"}
              },
          },
         "get_avg_of_grouped_records" => { 
              "$avg" => "$column_name" 
          },
         "count" => { "$sum" => 1 }
      }

  }
]

@array_of_objects = ModelName.collection.aggregate(stages, {:allow_disk_use => true})

Query stages
$match stage will apply conditions on query before fetching, so place it before other stages.
$group stage is used to group collection data, “_id” is used to set options on which you want to group records.
Error: A pipeline stage specification object must contain exactly one field. (16435)
As stages variable is array and you need to specify separate hash for each stage in it. Like in above query $match and $group are two stages both are placed in separate hashes and are separate elements of stages array.

Advertisements

I am Senior Software Engineer. I love reading, writing, sharing,developing, hiking, movies, trips, mountains, brooks, hills etc.

Tagged with: , ,
Posted in mongoid

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

StackOverFlow
Categories
Archives
%d bloggers like this: