MongoDB provides a lot of powerful aggregation tools in addition to the basic query functionality.
Count
Similar to SQL, used to count the sum of the number of documents in the collection:
Count can quickly return the number of documents regardless of the size of the collection.
You can add filter criteria, but you need to sacrifice query performance:
db.lf.count({"name":"rrrr"})
distinct
To find out all the different values for a given key, you must specify the collection and key when you use it:
Group
The group causes MongoDB to divide the collection into groups based on the differences of the selected key values, and then produce a result document by aggregating the documents within each group. Is it a little vague? Look at the following example:
db.runCommand({ "group": { "ns":"lf", "key":{"name":true}, "initial":{"count":0}, "$reduce":function(doc,prev) { prev.count++; }, "condition":{"age":{"$gt":20}} }})
Specify the collection to be grouped by NS:
"ns":"lf",
The basis for grouping documents by key:
"key":{"name":true},
This shows that all documents with the same value as the name key are divided into a group, and True indicates that the value of the key name is returned.
Initial represents initialization, which can be used to set the accumulator variable
"initial":{"count":0},
$reduce represents a function call
"$reduce":function(doc,prev){...}
condition is used to store filter conditions:
"condition":{"age":{"$gt":20}}
The result of the final execution is:
Finalize
The following is a complete finalize, which is used to streamline data from the database to the user, that is, to further filter the query results:
db.runcommand ({ "group" : { "ns" : "LF" , " key ": {" name ": true }, "initial" : {: 0 }, Span class= "hljs-string" > "$reduce" : function { prev.count++; }, "Finalize" : function< /span> { doc.num=doc.count; delete doc.count; }})
Finalize is able to modify the passed parameters and return the new values, with the following result:
$keyf
Sometimes groups are based on a complex condition, not just a key. For example, you would use Group to calculate multiple blog posts for each category. Because there are many authors, it is possible to classify articles in irregular case.
So, if you group by category name, the last "MongoDB" and "MongoDB" are different groups. To eliminate the effect of this case, define a function to determine the key that the document is based on. Define the groupings to use with $KEYF:
db.runCommand( { "group": { "ns":"lf", "$keyf":function(doc){return {"name":doc.username.toLowerCase()}}, "initial":{"count":0}, "$reduce":function(doc,prev) { prev.count++; } } })
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The aggregation of MongoDB