Recently has been using MongoDB, sometimes need to use statistics, on the Internet to check some information, the most suitable use is to use aggregate, the following introduction of their own use of experience.
Other people have written, I do not describe too much, we can search for more than n the same, I write my summary.
Basic knowledge
Please find more on your own, here are the key documents.
Operator Description:
$project: Include, exclude, rename, and display fields
$match: query, need the same parameters as find ()
$limit: Limit the number of results
$skip: Ignore the number of results
$sort: Sort results by a given field
$group: Combining results by given expression
$unwind: Split the embedded array into its own top-level file
Document: MongoDB official aggregate description.
Related use:
Db.collection.aggregate ([array]);
Array is any one or more operators.
The use of group and match is well understood using the Sqlserver,group usage, grouping statistics according to the specified column, the number of groupings can be counted, the and or the average of the groupings can be counted.
Group before the match, is to query the source data, group after the match is the group after the data filter;
Similarly, Sort,skip,limit is the same principle;
1 {_id:1,name: "a", Status:1,num:1}2 {_id:2,name: "a", Status:0,num:2}3 {_id:3,name: "B", Status:1,num:3} 4 {_id:4,name: "C", Status:1,num:4}5 {_id:5,name: "D", status:1,num:5}
The following is an example:
Application One: Statistics the number and total number of name;
Db.collection.aggregate ([
{$group: {_id: ' $name ', count:{$sum: 1},total:{$sum: ' $num '}}
]);
Application two: The number of the name of the statistic Status=1;
Db.collection.aggregate ([
{$match: {status:1}},
{$group: {_id: "$name", count:{$sum: 1}}}
]);
Application Three: Count the number of name, and the quantity is less than 2;
Db.collection.aggregate ([
{$group: {_id: ' $name ', count:{$sum: 1}},
{$match: {count:{$lt: 2}}}
]);
Application four: The number of the name of the statistic Stauts=1, and the quantity is 1;
Db.collection.aggregate ([
{$match: {status:1}},
{$group: {_id: "$name", count:{$sum: 1}},
{$match: {count:1}}
]);
Multi-column group, multi-column based on name and status
Db.collection.aggregate ([
{$group: {_id:{name: "$name", St: "$status"},count:{$sum: 1}}
]);
$project the operator is simple,
Db.collection.aggregate ([
{$project: {name:1,status:1}}
]);
As a result, only table data _id,name,status three fields, equivalent to the SQL expression select _id,name,status from collection
$unwind
This operator can split an array of documents into multiple documents, useful under special conditions, I have not done too much research.
The above basic can achieve most of the statistics, group pre-conditions, group after conditions, is the focus.