如何在mongodb中将字符串转换为数值 [英] how to convert string to numerical values in mongodb
问题描述
我正在尝试在MongoDB的聚合查询中将包含数字值的字符串转换为其值.
I am trying to convert a string that contains a numerical value to its value in an aggregate query in MongoDB.
文档示例
{
"_id": ObjectId("5522XXXXXXXXXXXX"),
"Date": "2015-04-05",
"PartnerID": "123456",
"moop": "1234"
}
我使用的汇总查询示例
{
aggregate: 'my_collection',
pipeline: [
{$match: {
Date :
{$gt:'2015-04-01',
$lt: '2015-04-05'
}}
},
{$group:
{_id: "$PartnerID",
total:{$sum:'$moop'}
}}]}
结果是
{
"result": [
{
"_id": "123456",
"total": NumberInt(0)
}
}
如何将字符串转换为数字值?
How can you convert the string to its numerical value?
推荐答案
MongoDB聚合不允许更改给定字段的现有数据类型.在这种情况下,您应该创建一些编程代码以将string
转换为int
.检查以下代码
MongoDB aggregation not allowed to change existing data type of given fields. In this case you should create some programming code to convert string
to int
. Check below code
db.collectionName.find().forEach(function(data) {
db.collectionName.update({
"_id": data._id,
"moop": data.moop
}, {
"$set": {
"PartnerID": parseInt(data.PartnerID)
}
});
})
如果集合的大小大于上述脚本的大小,则会降低性能,对于perfomace mongo,请提供
If your collections size more then above script will slow down the performance, for perfomace mongo provide mongo bulk operations, using mongo bulk operations also updated data type
var bulk = db.collectionName.initializeOrderedBulkOp();
var counter = 0;
db.collectionName.find().forEach(function(data) {
var updoc = {
"$set": {}
};
var myKey = "PartnerID";
updoc["$set"][myKey] = parseInt(data.PartnerID);
// queue the update
bulk.find({
"_id": data._id
}).update(updoc);
counter++;
// Drain and re-initialize every 1000 update statements
if (counter % 1000 == 0) {
bulk.execute();
bulk = db.collectionName.initializeOrderedBulkOp();
}
})
// Add the rest in the queue
if (counter % 1000 != 0) bulk.execute();
这基本上将发送到服务器的操作语句数量减少为每1000个排队的操作仅发送一次.
This basically reduces the amount of operations statements sent to the sever to only sending once every 1000 queued operations.
这篇关于如何在mongodb中将字符串转换为数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!