在MongoDB投影中将字符串转换为数字 [英] Convert a string to a number in MongoDB projection

查看:259
本文介绍了在MongoDB投影中将字符串转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文档集合,这些文档的值已知为数字,但存储为字符串.更改字段的类型是我无法控制的,但是我想在聚合中使用该字段(例如,将其取平均值).

I have a collection of documents that have a value that is known to be a number, but is stored as a string. It is out of my control to change the type of the field, but I want to use that field in an aggregation (say, to average it).

似乎我应该在分组之前使用投影,并在该投影中根据需要转换字段.我似乎无法正确掌握语法-我尝试的所有操作都给了我NaN,或者聚合的下一步中缺少新字段.

It seems that I should be using a projection prior to grouping, and in that projection convert the field as needed. I can't seem to get the syntax just right - everything I try either gives me NaN, or the new field is simply missing from the next step in the aggregation.

$project: {
    value: '$value',
    valueasnumber: ????
}

给出上面的非常简单的示例,其中所有文档中$ value的内容都是字符串类型,但是将解析为数字,我该怎么做才能使valueasnumber成为类型为double的新(不存在)字段带有解析后的$ value版本?

Given the very simple example above, where the contents of $value in all documents are string type, but will parse to a number, what do I do to make valueasnumber a new (non-existing) field that is of type double with the parsed version of $value in it?

我尝试了以下示例(以及大约十二种类似的事情):

I've tried things like the examples below (and about a dozen similar things):

{ $add: new Number('$value').valueOf() }
new Number('$value').valueOf()

我是否完全把错误的树都吠叫了?任何帮助将不胜感激!

Am I barking up the wrong tree entirely? Any help would be greatly appreciated!

(要100%清楚,以下是我想使用新字段的方式.)

(To be 100% clear, below is how I would like to use the new field).

$group {
    score: {
        $avg: '$valueasnumber'
    }
}

推荐答案

我能想到的一种方法是使用mongo shell javascript通过添加新的数字字段valuesasnumber(现有字符串的数字转换)来修改文档值"字段)在现有文档或新文档中.然后使用此数字字段进行进一步的计算.

One of the way which I can think of is to use a mongo shell javascript to modify the document by adding new number field, valuesasnumber (number conversion of existing string 'value' field) in the existing document or in the new doc. Then using this numeric field for further calculations.

db.numbertest.find().forEach(function(doc) {
    doc.valueasnumber = new NumberInt(doc.value);
    db.numbertest.save(doc);
});

使用valueasnumber字段进行数值计算

Using the valueasnumber field for numeric calculation

db.numbertest.aggregate([{$group : 
   {_id : null, 
    "score" : {$avg : "$valueasnumber"}
   }
}]);

这篇关于在MongoDB投影中将字符串转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆