Lucky7Chess
Lucky7Chess

Reputation: 33

MongoDB (Node.js) returning data to an array

So I have this set of data in a mongo collection, and I need the temperature and time to be returned in separate array for a device I ask for.

device01t: [32.00, 42.00] device01d: [date, date] or device02t [22.00, 43.00] etc.

{
    "_id" : "device01",
    "event" : [
            {
                    "temperature" : "32.00",
                    "when" : ISODate("2016-07-02T00:21:41.441Z")
            },
            {
                    "temperature" : "42.00",
                    "when" : ISODate("2016-07-02T00:21:46.766Z")
            },             
    ]
}
 {
    "_id" : "device02",
    "event" : [
            {
                    "temperature" : "22.00",
                    "when" : ISODate("2016-06-02T00:21:41.441Z")
            },
            {
                    "temperature" : "43.00",
                    "when" : ISODate("2016-07-02T00:21:46.766Z")
            },             
    ]
}

I am using mqtt(irrelevant to the question), but I'm posting the data into the collection using

collection.update(  
  { _id:key },  //key extracted from device topic
  { $push:  { event: { value:String(payload), when:new Date() } }  },
  { upsert:true },

I tried using Node.js code (default MongoDB driver) to extract the temperature values of a device:

var resultArray = [];
    mongo.connect(url, function(err, db) {
    var cursor = db.collection('test_mqtt').find({"_id":"device01"},{"event.value":1,"_id":0});
         cursor.forEach(function(doc, err) {
         resultArray.push(doc.event);
}, function() {
  db.close();
  console.log(resultArray);
});

but this doesn't get back an array with each value in its own slot like I intended. Should the schema be changed or am I missing something about how Mongo's find() works?

Upvotes: 0

Views: 176

Answers (1)

Paul S.
Paul S.

Reputation: 66324

With .aggregate we have $unwind and $group which may be useful here

db.collection('test_mqtt').aggregate([
    {$unwind: '$event'},
    {$group: {
        _id: '$_id',
        t: {$push: '$event.temperature'}
        d: {$push: '$event.when'}
    }}
]);
/*
[{
    _id: "device01",
    t: ["32.00", "42.00"],
    d: [ISODate("2016-07-02T00:21:41.441Z"), ISODate("2016-07-02T00:21:46.766Z")]
}, {
   ...
}]
*/

Upvotes: 2

Related Questions