Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert string to numerical values in mongodb

I am trying to convert a string that contains a numerical value to its value in an aggregate query in MongoDB.

Example of document

{ "_id": ObjectId("5522XXXXXXXXXXXX"),    "Date": "2015-04-05",    "PartnerID": "123456",    "moop": "1234"  } 

Example of the aggregate query I use

{     aggregate: 'my_collection',     pipeline: [          {$match: {              Date :                    {$gt:'2015-04-01',                    $lt: '2015-04-05'                   }}              },          {$group:              {_id: "$PartnerID",               total:{$sum:'$moop'}              }}]} 

where the results are

{    "result": [      {        "_id": "123456",        "total": NumberInt(0)      } } 

How can you convert the string to its numerical value?

like image 996
Naftsen Avatar asked Apr 07 '15 08:04

Naftsen


People also ask

How do I convert a string to a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.

Which function converts a string value into numeric value?

The ToNumber function converts a string of characters to its applicable numeric value.

How do I change the datatype of a column in MongoDB?

You can change the data type of a field by using the data type selectors on the right of the field in the Atlas Cloud Cluster as well as MongoDB Compass . If you want to update it using Mongo shell or any specific drivers of MongoDB then you can refer to the $convert operator.

Which file in the MongoDB directory holds the MongoDB daemon?

MongoDB's default data directory path is /data/db on the drive.


2 Answers

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)         }     }); }) 

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(); 

This basically reduces the amount of operations statements sent to the sever to only sending once every 1000 queued operations.

like image 94
Yogesh Avatar answered Oct 05 '22 14:10

Yogesh


You can easily convert the string data type to numerical data type.

Don't forget to change collectionName & FieldName. for ex : CollectionNmae : Users & FieldName : Contactno.

Try this query..

db.collectionName.find().forEach( function (x) { x.FieldName = parseInt(x.FieldName); db.collectionName.save(x); }); 
like image 39
Amarendra Kumar Avatar answered Oct 05 '22 15:10

Amarendra Kumar