Pregunta

I'm using the Node MongoDB driver to collect analytics for my website and send them to MongoLab. How does one insert the current datetime into a document so it can later be used to do aggregation in Mongo?

To be clear, here is the code:

var query = {};
query['date_time'] = new Date();
Db.connect(mongoUri, function (err, db) {
        if (!err) {
            db.collection(analyticsCollection, function (err, coll) {
                if (!err) {
                    coll.save(query, {safe:true}, function (err, result) {
                        db.close();
                        res.send(200,result);
                        //console.log(result);
                    });
                } else {
                    res.json(503,{errno:503,msg:'error: collection does not exist.'});
                }
            });
        } else {
            res.json(503,{errno:503,msg:'error: database does not exist.'});
        }
    });

The MongoDB documentation describes how to create a BSON date in the mongo shell, but not in the Node driver and I can't find it in the Node driver docs either.

¿Fue útil?

Solución

I found a way to do what I wanted to do. This seems kind of klugey to me, so if anyone can find a better way, please let me know. My solution uses the underscore.js library:

var _ = require('underscore');
vary query = {}
query['foo'] = 'bar'

Db.connect(mongoUri, function (err, db) {
        if (!err) {
            db.collection(analyticsCollection, function (err, coll) {
                if (!err) {
                    coll.save(_.extend(query,{"datetime":new Date()}), {safe:true}, function (err, result) {
                        db.close();
                        res.send(200,result);
                        //console.log(result);
                    });
                } else {
                    res.json(503,{errno:503,msg:'error: collection does not exist.'});
                }
            });
        } else {
            res.json(503,{errno:503,msg:'error: database does not exist.'});
        }
    });

Now I can do the aggregation (without needing to use the $project operator):

> db.analytics.aggregate([{$group:{_id:{day:{$dayOfMonth:"$datetime"}}}}])
{ "result" : [ { "_id" : { "day" : 15 } } ], "ok" : 1 }

Hope this helps someone.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top