Similar functions of mongodb mapreduce, aggregate, group

(1) Define map and reduce functions first

m = function () {

    emit(this.carrier, this.impCount);
};
r = function (key, values) {
    var x = 0;
    values.forEach(function (v) {x += v;});
    return x;
};


The first command, call runCommand:

res = db.runCommand({
    mapreduce:"test_table",
    map:m,
    reduce:r,
    query : {
        '$or' : [{'impCount': {'$gt' : 3}},{'impCount': {'$lt' : 16}}],
},
    out:"students_res"
    });
    
第二中命令, 调用 mapreduce函数:
res = db.test_table.mapReduce(m,r,{
    query : {
         '$or' : [{'impCount': {'$gt' : 3}},{'impCount': {'$lt' : 16}}],
        },
    out:"students_res"

    }  );

(2) 

 var key1 =  { var1 : "$appid", var2 : "$os"}

var query1 = { '$or' : [{'impCount': {'$gt' : 3}},{'impCount': {'$lt' : 16}}] }
var sort1 =  { carrier: -1 }
var limit = 3

db.test_table.aggregate(
[
       { $match:  match1},
       { $group:  { _id: key1 , ImpCount: { $sum: "$impCount" }, ClickCount:{$sum: "$clickCount" }}},
       { $sort:   sort1},
       { $limit:  limit }
]
);

(3)

var key1 = {'carrier' : true};

var query1 = { '$or' : [{'impCount': {'$gt' : 16}},{'impCount': {'$lt' : 3}}] };

db.test_table.group({

     key : key1,

     cond: query1,

     reduce: function (obj, prev) {prev.msum + = obj.impCount; }, initial: {msum: 0}

}

);

Guess you like

Origin blog.csdn.net/zgb40302/article/details/50404827