[英]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. 因此,我将这组数据存储在mongo集合中,我需要将温度和时间以单独的数组形式返回给我要的设备。
device01t: [32.00, 42.00] device01d: [date, date] or device02t [22.00, 43.00] etc. 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")
},
]
}
I am using mqtt(irrelevant to the question), but I'm posting the data into the collection using 我正在使用mqtt(与问题无关),但是我正在使用以下方法将数据发布到集合中
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: 我尝试使用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);
});
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? 应该更改架构还是我缺少有关Mongo的find()工作原理的信息?
With .aggregate
we have $unwind
and $group
which may be useful here 使用.aggregate
我们有$unwind
和$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")]
}, {
...
}]
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.