MongoDB (Node.js) 返回数据到数组

MongoDB (Node.js) returning data to an array

所以我在 mongo 集合中有这组数据,我需要在单独的数组中为我要求的设备返回温度和时间。

device01t: [32.00, 42.00] device01d: [date, date] 或 device02t [22.00, 43.00] 等

{
    "_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")
            },             
    ]
}

我正在使用 mqtt(与问题无关),但我正在使用

将数据发布到集合中
collection.update(  
  { _id:key },  //key extracted from device topic
  { $push:  { event: { value:String(payload), when:new Date() } }  },
  { upsert:true },

我尝试使用 Node.js 代码(默认 MongoDB 驱动程序)提取设备的温度值:

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);
});

但这并没有像我预期的那样返回一个数组,每个值都在它自己的槽中。应该更改模式还是我遗漏了一些关于 Mongo 的 find() 工作原理的信息?

有了 .aggregate 我们有 $unwind and $group 这可能在这里有用

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")]
}, {
   ...
}]
*/