0

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?

1 Answer 1

2

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")]
}, {
   ...
}]
*/
Sign up to request clarification or add additional context in comments.

3 Comments

Definitely sending it in the right direction, but i'm getting an "unexpected identifier" error for t and d?
OK, so I'm pulling my hair out lol. How would I get the array data for a specific device/ id?
arr.find(x => x._id === 'foo'), where arr looks like [{_id: 'foo'}]. When I'm trying to build aggregates I use robomongo to try them out and see what the data structure looks like. The key is logging everything you need to know the value/structure of

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.