问题描述
我想将MongoDB值字段的字符串转换为整数,然后计算平均值.
I want to convert the string of a MongoDB value field to integers and then calculate the average.
这是我的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"
}
]
}
]
}
我正在使用以下查询来提取平均值
I am using the following query to extract average values
-
查询:
Query:
db.collection_name.aggregate( [{ '$project': { 'values': '$data.Cables.Value', }}, { '$unwind': '$values' }, { '$addFields': { 'avgValue': { '$avg': { $toInt: '$values' } } } } ] )
但是我得到这个错误:
我还尝试了以下方法:
I 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:
期望值应为值字段的平均值.
我需要对嵌套文档值进行某种转换.
The expected value should be the average of the values fields.
I need some kind of conversion for nested document values.
输入的字符串值必须转换为整数或小数,然后应计算其平均值.
The incoming string value has to be converted into integers or decimals and then the average of it should be calculated.
然后在C#代码中使用它来生成管道
This is then used in C# code to generate the pipeline
var pipeline = new[]
{
project, unwind, addfields
};
推荐答案
使用 toDouble
代替 toInt
,因为您的值不是整数.请尝试以下步骤.
Use toDouble
instead of toInt
because your values are not integers. Try the stages below.
[
{
'$project': {
'values': '$data.Cables.Value'
}
}, {
'$unwind': {
'path': '$values'
}
}, {
'$project': {
'values': {
'$map': {
'input': '$values',
'as': 'value',
'in': {
'$toDouble': '$$value'
}
}
}
}
}, {
'$addFields': {
'avgValue': {
'$avg': '$values'
}
}
}
]
这篇关于MongoDB字符串转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!