我想将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' } } } } ] )
But I get this error:
2019-01-29T11:06:05.642-0800 E QUERY [js] Error: command failed:
{
"ok" : 0,
"errmsg" : "Unsupported conversion from array to int in $convert
with no onError value",
"code" : 241,
"codeName" : "ConversionFailure"
} : aggregate failed :
_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
@(shell):1:1I also tried the following:
db.collection_name.aggregate( [{ '$project': { 'values': '$data.Cables.Value', }}, { '$unwind': '$values' }, { '$addFields': { 'avgValue': { '$avg': { 'input': '$values', 'to': 'int' } } } } ] )
But I'm also getting this output:
{ "_id" : ObjectId("5c509604fc007808c427edcb"), "values" :
[ "24.3", "23.3", "25.3", "31.3", "90.3" ], "avgValue" : null }
预期值应该是数值字段的平均值。
我需要某种嵌套文档值的转换。
输入的字符串值必须转换为整数或小数,然后计算它们的平均值。
然后,这将用于C#代码生成管道。
var pipeline = new[]
{
project, unwind, addfields
};