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?
It should be saved. It should be like this :
Eventually I used
to turn
moop
from string to integer in my_collection following the example in Simone's answer MongoDB: How to change the type of a field?.Collation is what you need:
Three things need to care for:
MongoDB aggregation not allowed to change existing data type of given fields. In this case you should create some programming code to convert
string
toint
. Check below codeIf 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
This basically reduces the amount of operations statements sent to the sever to only sending once every 1000 queued operations.