我想将MongoDB值字段的字符串转换为整数,然后计算平均值。
这是我的 JSON:
"_id" : ObjectId("5c49f398fc0078178c76705b"), // my json data
"Time_Created" : ISODate("2019-01-24T17:19:20.205Z"), // date
"Test_ID" : "1",
"data" : [
{
"Device_id" : "1",
"Total_wires" : "5",
"Cables" : [
{
"TAG" : "4001",
"Value" : "24.3"
},
{
"TAG" : "4002",
"Value" : "21.3"
},
{
"TAG" : "4003",
"Value" : "21.3"
},
{
"TAG" : "4004",
"Value" : "21.3"
},
{
"TAG" : "4005",
"Value" : "100.3"
}
]
}
]
}
我正在使用以下查询来提取平均值
-
Query:
db.collection_name.aggregate( [{ '$project': { 'values': '$data.Cables.Value', }}, { '$unwind': '$values' }, { '$addFields': { 'avgValue': { '$avg': { $toInt: '$values' } } } } ] )
但我收到这个错误:
2019-01-29T11:06:05.642-0800 E 查询 [js] 错误:命令失败:
{
“好的”:0,
"errmsg" : "$convert 中不支持从数组到 int 的转换
没有 onError 值”,
“代码”:241,
"codeName" : "转换失败"
}:聚合失败:
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:534:17
assert.commandWorked@src/mongo/shell/assert.js:618:16
DB.prototype._runAggregate@src/mongo/shell/db.js:260:9
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1062:12
@(外壳):1:1
-
我还尝试了以下方法:
db.collection_name.aggregate(
[{ '$project': { 'values': '$data.Cables.Value', }},
{ '$unwind': '$values' },
{ '$addFields': { 'avgValue': { '$avg': { 'input': '$values', 'to':
'int' } } } }
] )
但我也得到这个输出:
{“_id”:ObjectId(“5c509604fc007808c427edcb”),“值”:
[“24.3”、“23.3”、“25.3”、“31.3”、“90.3”]、“avgValue”:空
}
预期值应该是值字段的平均值。
我需要对嵌套文档值进行某种转换。
传入的字符串值必须转换为整数或小数,然后计算其平均值。
然后在 C# 代码中使用它来生成管道
var pipeline = new[]
{
project, unwind, addfields
};