Mongodb Aggregate functions 1. the count function is very understandable. Like other databases, it is used to perform the count operation selectcount (*) fromtab1db. the tab1.count () and above examples are quite understandable, but if there are operations such as skip and limit in the operation, count will ignore these operations and a true parameter must be added, such as: d
Mongodb Aggregate functions 1. the count function is very understandable. Like other databases, it is used to perform the count operation select count (*) from tab1 = db. the tab1.count () and above examples are quite understandable, but if there are operations such as skip and limit in the operation, count will ignore these operations and a true parameter must be added, such as: d
Mongodb Aggregate functions
1. count
This function is easy to understand. Like other databases, it performs a count operation.
Select count (*) from tab1 = db. tab1.count ()
The preceding example is easy to understand. However, if the operation involves operations such as skip and limit, count will ignore these operations and a true parameter must be added.
For example, db. tab1.find (). skip (1), limit (2). count () and db. tab1.find (). count () have the same results.
Must be modified to db. tab1.find (). skip (1). limit (2). count (true)
2. distinct
De-duplicated functions, which should also be familiar with, and various relational databases have
Specific Operation: db. runCommand ({"distinct": "collection", "key": "xxxx"}) = db. collections. distinct ("xxxx ");
3. group
Select a, B, sum (c) csum from coll where active = 1 group by a, B
Db. coll. group ({key: {a: true, B: true },
Cond: {active: 1 },
Reduce: function (obj, prev) {prev. csum + = obj. c ;},
Initial: {csum: 0}
});
Parameter description:
Key: group field
Reduce: an aggregate function. Typical sum and count operations include two parameters: the current traversal object and the aggregation counter.
Initial: Initialize counter value
Cond: Query condition filtering option. If it is null, all rows of the current collection are operated by default.
The Group cannot be used in sharding, and the result output cannot contain more than 10000 keys.
Example:
> Db. mtb1.find ()
{"_ Id": ObjectId ("4fb4be52aa814943b788095c"), "name": "aaa", "score": 77}
{"_ Id": ObjectId ("4fb4be5caa814943b788095d"), "name": "bbb", "score": 79}
{"_ Id": ObjectId ("4fb4be61aa814943b788095e"), "name": "ccc", "score": 79}
{"_ Id": ObjectId ("4fb4be69aa814943b788095f"), "name": "ddd", "score": 79}
{& Quot; _ id & quot;: ObjectId (& quot; 4fb4be74aa814943b7880960 & quot;), & quot; name & quot;: & quot; eee & quot;, & quot; score & quot;: 100}
{"_ Id": ObjectId ("4fb4be7aaa814943b7880961"), "name": "fff", "score": 100}
{"_ Id": ObjectId ("4fb4be82aa814943b7880962"), "name": "ggg", "score": 100}
{"_ Id": ObjectId ("4fb4be9eaa814943b7880963"), "name": "hhh", "score": 200}
> Db. mtb1.group (
... {Key: {score: true },
... Reduce: function (obj, prev) {prev. count ++ ;},
... Initial: {count: 0}
...});
[
{
"Score": 77,
"Count": 1
},
{
"Score": 79,
"Count": 3
},
{
"Score": 100,
"Count": 3
},
{
"Score": 200,
"Count": 1
}
]
A simple example should be clear. In fact, the group is still built on reduce.
4. map/reduce
The function of this tool can implement any of the above three types. It is completed in two steps: map first, reduce, map first, and map, then reduce will be performed. After map, key-values will be generated, such as {key: [value1, value2, value3. ..]}. then, the reduce operation is used to obtain the key-value, that is, a single value.
Syntax:
Db. runCommand (
{Mapreduce: ,
Map: ,
Reduce:
[, Query: ]
[, Sort: ]
[, Limit: ]
[, Out: ]
[, Keeptemp: ]
[, Finalize: ]
[, Scope:]
[, Verbose: true]
}
);
Query is very common. It is used to filter query conditions in the map stage to limit the record range of MapReduce operations. It is used by sort and limit set query.
Out: the collections name of the output result.
Keeptemp boolean type. The default value is false. If it is true, the generated collection will exist permanently. If it is false, the generated collection will be automatically deleted after the client connection is closed.
Finalize is generally used to calculate the average, crop the array, and clear unnecessary information.
Query is very common. It is used to filter query conditions in the map stage to limit the record range of MapReduce operations. It is used by sort and limit set query.
Out: the collections name of the output result.
Keeptemp boolean type. The default value is false. If it is true, the generated collection will exist permanently. If it is false, the generated collection will be automatically deleted after the client connection is closed.
Finalize is generally used to calculate the average, crop the array, and clear unnecessary information.
{Result: ,
Counts :{
Input: ,
Emit: ,
Output:
},
TimeMillis: ,
OK: <1_if_ OK>,
[, Err: ]
}
Result: The name of the collection that stores the result.
Input: number of rows meeting the condition
Emit: the number of emit calls, that is, the total amount of data in all sets.
Ouput: number of returned results
TimeMillis: execution time, in milliseconds
OK: whether the operation is successful. The success value is 1.
Err: if it fails, there may be reasons for failure.
An example of the official document is provided:
$./Mongo
> Db. things. insert ({_ id: 1, tags: ['Dog', 'cat']});
> Db. things. insert ({_ id: 2, tags: ['cat']});
> Db. things. insert ({_ id: 3, tags: ['mouse ', 'cat', 'dog']});
> Db. things. insert ({_ id: 4, tags: []});
> // Map function
> M = function (){
... This. tags. forEach (
... Function (z ){
... Emit (z, {count: 1 });
...}
...);
...};
> // Reduce function
> R = function (key, values ){
... Var total = 0;
... For (var I = 0; I
... Total + = values [I]. count;
... Return {count: total };
...};
> Res = db. things. mapReduce (m, r );
> Res
{"TimeMillis. emit": 9, "result": "mr. things.1254426454.3 ",
"NumObjects": 4, "timeMillis": 9, "errmsg": "", "OK": 0}
> Db [res. result]. find ()
{"_ Id": "cat", "value": {"count": 3 }}
{"_ Id": "dog", "value": {"count": 2 }}
{"_ Id": "mouse", "value": {"count": 1 }}
> Db [res. result]. drop ()