简体   繁体   中英

mongoose pre-aggregated reports

Following official mongodb docs ( http://docs.mongodb.org/manual/use-cases/pre-aggregated-reports/#log-an-event ) i'm trying to setup the same in nodejs + mongoose but there is a problem that i cannot figure out.

Problem is in $inc key : value, i cannot compute dynamic key like its already done in python:

 update = { '$inc': {
            'hourly.%d' % (hour,): 1,
            'minute.%d.%d' % (hour,minute): 1 } 
 }

My code looks like :

var daily_schema = mongoose.Schema({
    _id: 'string',
    metadata: {
        date: { type: 'date', default: Date.now() },
        site: 'string',
        page: 'string'
    },
    hourly: 'object',
    minute: 'object'    
});

var daily_stats = mdb.model('hits', daily_schema);

var date = new Date();
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var year = date.getFullYear();

daily_stats.update({
    _id : year + '/' + data.xid + '/' + data.url,
    metadata : {
        date : date,
        site : data.xid,
        page : data.url
    }
    },
    {
    $inc: { 
        'hourly.' + hour : 1, // (python: 'hourly.%d' % (hour,): 1,) how about javascript?
        'minute.' + hour + '.' + minute : 1
    }
    },
    { upsert: true }, function(err) {
        if (err) { console.log("daily_stats:upsert:error"); console.log(err) } else {
        console.log("daily_stats:upsert:ok");
    }           
    }
);

Please give me a hint how this can be done in javascript?

Best regards & thanks to all!

You need to first build up your $inc object programmatically and then include that in your update call.

var inc = { $inc: {} };
inc.$inc['hourly.' + hour] = 1;
inc.$inc['minute.' + hour + '.' + minute] = 1;

daily_stats.update({
    _id : year + '/' + data.xid + '/' + data.url,
    metadata : {
        date : date,
        site : data.xid,
        page : data.url
    }},
    inc,
    { upsert: true }, function(err) {
        if (err) { console.log("daily_stats:upsert:error"); console.log(err) } else {
        console.log("daily_stats:upsert:ok");
    }           
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM