1, Count: Query the number of records
Db.user.count ()
It can be as conditional as find.
Db.user.count ({"Age":$})
2. Distinct: Used to find all the different values of a given key
Db.user.distinct ("num")
3, group: Group Query
Key: The field used to group the document, we are here for the age group
Initial: Each group shares an "initialization function"
$reduce: The reduce function is executed, the first parameter is the current document object, the second parameter is the cumulative object of the last function operation, how many documents, how many times will the $reduce be called
Db.user.group ({"key": {"Age":true}, "initial": {"person": []}," $reduce": Function (cur,prev) { prev.person.push (cur.name);}})
If you want to filter out the age of less than 20, group has two optional parameters: condition and Finalize
Condition: Conditions for performing filters
Finalize: At reduce execution completion, the result set returns the function that was eventually executed against the result set.
Db.user.group ({"Key":{" Age":true},"Initial":{" Person":[]},"$reduce": Function (Doc, out){ out. Person.push (Doc.name);},"Finalize": Function ( out){ out. count= out. Person.length;},"condition":{" Age": {$lt: -}}})
4. MapReduce:
The MapReduce in MongoDB corresponds to group by in the relational database.
Parameters:
Map function: This is called the mapping function, which calls emit (Key,value), and the collection is grouped according to the key you specify.
Reduce function: This is called the simplification function, the data grouped by the map is grouped to simplify, note: The key in reduce (Key,value) is emit in the Key,vlaue is the emit group after the emit (value) of the collection.
MapReduce function: This is the last function to execute, with parameters of map,reduce and some optional parameters.
Example:
Map function, dealing with age greater than 10:
var m=function () { if(this .age>) { emit ( this. Age,{name:this. name});} }
Reduce function:
var r=var count=0; Values.foreach (function () {count+ =1 return count ;}
Perform:
Db.user.mapReduce (m,r,{"out":"collection"})
To view the output set "Collecton" case
Db.collection.find ()
As can be seen from the result set, the _id in the temporary result set is the key in the emit function.
We can see the following information:
Result: "Stored collection name".
Input: The number of incoming documents.
Emit: The number of times this function was called.
Reduce: The number of times this function was called.
Output: Returns the number of documents at the end.
MongoDB Aggregation Operations