MongoDB Group Statistics Group

Source: Internet
Author: User

The grouping aggregation in MongoDB is $group, it cannot be sort, using the following format:

{$group: {_id: <expression>, <field1>: {<accumulator1>: <expression1>}, ...}}

Where the _id attribute is required, the purpose is to specify the field or basis of the grouping, field1 for the custom field, accumulator for the accumulator, the following to count the number of user registrations per day as a column

Db.user.aggregate ([    {        $group: {            _id:{                year:{$year: ' $time '},//time for the registered time $year represents the year of acquisition                month:{$ Month: "$time"},//$month get the month                day:{$dayOfMonth: "$time"}//$dayOfMonth get the number            }            count:{$sum: 1}//$sum is cumulative, 1 = cumulative number        }    }])

If you only want to register the area for Sichuan, then add a $match before $goup:

{    $match: {location         : ' Sichuan '}    },

The Java implementation of the above two aggregation operations:

DBObject Filtercond =NewBasicdbobject (); Filtercond.put ("Location", "Sichuan");D bobject match=NewBasicdbobject ("$match", Filtercond);D bobject Group=Newbasicdbobject ();D bobject groupdate=NewBasicdbobject (); Groupdate.put ("Year",NewBasicdbobject ("$year", "$time")); Groupdate.put ("Month",NewBasicdbobject ("$month", "$time")); Groupdate.put ("Day",NewBasicdbobject ("$dayOfMonth", "$time")); Group.put ("$group",NewBasicdbobject ("_id", Groupdate));
== Output.results (). iterator ();

The first time to write a blog, only to find language organization ability really poor, exhausted, work ~ ~ ~

For more aggregation operations see this "http://docs.mongodb.org/manual/reference/operator/aggregation-pipeline/"

MongoDB Group Statistics Group

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.