Insert test data first:
For (VAR I = 1; I <20; I ++ ){
VaR num = I % 6;
DB. Test. insert ({_ ID: I, name: "User _" + I, age: num });
}
1. Common grouping query (http://www.my400800.cn)
DB. Test. Group ({key: {age: true}, initial: {num: 0}, $ reduce: function (Doc, Prev ){
Prev. Num ++
}});
DB. runcommand ({group:
{
NS: "test ",
Key: {age: true },
Initial: {num: 0 },
$ Reduce: function (Doc, Prev ){
Prev. Num ++}
}
});
2. filter and then group
DB. Test. Group ({key: {age: true}, initial: {num: 0}, $ reduce: function (Doc, Prev ){
Prev. Num ++
},
Condition: {age :{$ GT: 2 }}
});
DB. runcommand ({group:
{
NS: "test ",
Key: {age: true },
Initial: {num: 0 },
$ Reduce: function (Doc, Prev ){
Prev. Num ++ },
Condition: {age :{$ GT: 2 }}
}
});
Common $ where queries:
DB. Test. Find ({$ where: function (){
Return this. age> 2;
}
});
Group join $ where Query
DB. Test. Group ({key: {age: true}, initial: {num: 0}, $ reduce: function (Doc, Prev ){
Prev. Num ++
},
Condition: {$ where: function (){
Return this. age> 2;
}
}
});
3. grouping with function return values
// Note that the $ keyf specified function must return an object.
DB. test. group ({$ keyf: function (DOC) {return {age: Doc. age };}, initial: {num: 0}, $ reduce: function (Doc, Prev ){
Prev. Num ++
}
});
DB. runcommand ({group:
{
NS: "test ",
$ Keyf: function (DOC) {return {age: Doc. Age };},
Initial: {num: 0 },
$ Reduce: function (Doc, Prev ){
Prev. Num ++}
}
});
4. Use the Terminator
DB. test. group ({$ keyf: function (DOC) {return {age: Doc. age };}, initial: {num: 0}, $ reduce: function (Doc, Prev ){
Prev. Num ++
},
Finalize: function (DOC) {Doc. Count = Doc. Num; Delete Doc. Num ;}
});
DB. runcommand ({group:
{
NS: "test ",
$ Keyf: function (DOC) {return {age: Doc. Age };},
Initial: {num: 0 },
$ Reduce: function (Doc, Prev ){
Prev. Num ++ },
Finalize: function (DOC) {Doc. Count = Doc. Num; Delete Doc. Num ;}
}
});