假设我有一个看起来像这样的收藏:
{
"_id": ObjectId(...),
"recorded": ISODate("2018-05-05T11:05:32.000"),
"devices": [
{
"id": "KSA2",
"temp": 32,
"ttl": 10
},
{
"id": "KSA24",
"temp": 28,
"ttl": 10
}
]
}
{
"_id": ObjectId(...),
"recorded": ISODate("2018-05-05T18:23:45.000"),
"devices": [
{
"id": "KSA2",
"temp": 31,
"ttl": 10
},
{
"id": "KSA24",
"temp": 16,
"ttl": 10
}
]
}我需要做的是通过设备将其转换为文档:
{
"Devices": [
{
"id": "KSA2",
"observations": [
{
"time":ISODate("2018-05-05T11:05:32.000"),
"temp":32,
"ttl":10
}
{
"time":ISODate("2018-05-05T18:23:45.000"),
"temp":31,
"ttl":10
}
]
},
{
"id":"KSA24",
...
}
]
}这是否可以使用聚合框架“在”mongodb中完成,或者我是否需要在外部使用Python或类似的东西来完成这个任务?
发布于 2018-09-24 09:06:05
在集合上运行以下聚合:
db['myCollection'].aggregate(
[
{
$unwind: {
path : "$devices",
}
},
{
$group: {
_id : "$devices.id",
observations : {$push :
{
time : "$recorded",
temp:"$devices.temp",
ttl:"$devices.ttl"}
}
}
},
{
$out: "devices"
},
],
);使用的阶段:
这将在设备集合中输出:
db['devices'].find();
{
"_id" : "KSA24",
"observations" : [
{
"time" : ISODate("2018-05-05T13:05:32.000+0200"),
"temp" : 28.0,
"ttl" : 10.0
},
{
"time" : ISODate("2018-05-05T20:23:45.000+0200"),
"temp" : 16.0,
"ttl" : 10.0
}
]
}
{
"_id" : "KSA2",
"observations" : [
{
"time" : ISODate("2018-05-05T13:05:32.000+0200"),
"temp" : 32.0,
"ttl" : 10.0
},
{
"time" : ISODate("2018-05-05T20:23:45.000+0200"),
"temp" : 31.0,
"ttl" : 10.0
}
]
}之后,使用新设备集合,或将其重命名为旧名称。
https://stackoverflow.com/questions/52474143
复制相似问题