我是 mongoDB 菜鸟,你可以在最后找到 mongoDB 文档示例。
我想根据 metadata.sensorId 将 data.conclusion 乘以对象 coef 中存储的值。 在示例中,metadata.sensorId 是“SENSOR_32”,因此我们要相乘的系数是 1.2。
例如,相乘的值将存储为另一个新字段“multiplied_conclusion”。
我该怎么做。
{
"metadata": {
"sensorId": "SENSOR_32"
},
"data": {
"consumption": 3.547,
"powerOutput": 21.282
},
"coef": {
"SENSOR_32": 1.2,
"SENSOR_33": 1.32,
"SENSOR_34": 1.62,
"SENSOR_35": 2.3,
"SENSOR_36": 2.47,
"SENSOR_37": 2.46,
"SENSOR_38": 1.62
}
}
可以通过将
coef
转换为数组,然后获取传感器名称与 coef
匹配的特定 key 来找到所需的 metadata.sensorId
。此管道显示了所有步骤,为您的示例提供了 4.2564 (1.2 * 3.547)
的结果:
db.collection.aggregate([
{ $set: { coef_arr: { $objectToArray: "$coef" } } },
{
$set: {
reqd_coef: {
$first: {
$filter: {
input: "$coef_arr",
cond: { $eq: ["$$this.k", "$metadata.sensorId"] }
}
}
}
}
},
{
$set: {
multiplied_consumption: {
$multiply: ["$reqd_coef.v", "$data.consumption"]
}
}
}
])
这个管道通过合并一步完成: