MongoDB——aggregate。

Basic knowledge

Please find more by yourself, the following are the key documents.

Operator introduction:

  • $project: include, exclude, rename and display fields
  • $match: query, requires the same parameters as find()
  • $limit: limit the number of results
  • $skip: number of skipped results
  • $sort: sort the results by the given field
  • $group: Group the results according to the given expression
  • $unwind: split the embedded array into its own top-level file

 

Documentation: MongoDB official aggregate description .

 

Related use:

db.collection.aggregate([array]);

 

array can be any one or more operators.

The usage of group and match, I have used sqlserver, and the usage of group is well understood. According to the specified column, the grouping statistics can be counted, the number of groups can be counted, and the sum or average value of the groups can be counted.

The match before the group is to query the source data, and the match after the group is to filter the data after the group;

In the same way, sort, skip, limit are also 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}

 

 

Here is an example:

Application 1: Count the number and total number of names;

db.collection.aggregate([

  {$group:{_id:"$name",count:{$sum:1},total:{$sum:"$num"}}

]);

Application 2: Count the number of names with status=1;

db.collection.aggregate([

  {$match:{status:1}},

  {$group:{_id:"$name",count:{$sum:1}}}

]);

Application 3: Count the number of names, and the number is less than 2;

db.collection.aggregate([

  {$group:{_id:"$name",count:{$sum:1}},

  {$match:{count:{$lt:2}}}

]);

Application 4: Count the number of names with stauts=1, and the number is 1;

db.collection.aggregate([

  {$match:{status:1}},

  {$group:{_id:"$name",count:{$sum:1}}},

  {$match:{count:1}}

]);

 

Multi-column group, multi-column according to name and status

db.collection.aggregate([

  {$group:{_id:{name:"$name",st:"$status"},count:{$sum:1}}}

]);

 

The $project operator is very simple,

db.collection.aggregate([

  {$project:{name:1,status:1}}

]);

The result is that there are only table data with three fields of _id, name and status, which is equivalent to the sql expression select _id, name, status from collection

 

$unwind

This operator can split an array of documents into multiple documents, which is useful under special conditions. I haven't done much research yet.


The above can basically realize most of the statistics, the pre-group condition and the post-group condition are the key points.


Reprinted: http://www.cnblogs.com/fycayy/p/3850973.html?utm_source=tuicool&utm_medium=referral

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324696113&siteId=291194637