Type conversation from string to number

Hello, could you please help me…
I am trying to perform a sum using a field that is string example:

db.Compras.aggregate([
{
$group: {
_id: { Agente: “$comercio.agente.idAgente” },
total: { $sum:‘$compra.montoTotal’ }
}
}
]);

How can I convert “compra.montoTotal” to int within this query?
Preserving the group

Hello @edith_t, Welcome back the the MongoDB community forum,

You can use $toInt or $toDecimal operator to convert type something like this,

db.Compras.aggregate([
  {
    $group: {
      _id: { Agente: "$comercio.agente.idAgente" },
      total: { $sum: { $toDecimal: "$compra.montoTotal" } }
    }
  }
]);
2 Likes

While you may make the conversion in real time as shown by @turivishal, I think it would be best to permanently convert you field montoTotal to the appropriate number type.

The field would take less space.

Your code will be more efficient since you will not convert every time you compute with it.

Natural sorting order is correct for numbers but not for string:

The string “10.50” is less than the string “9.50” but the number 10.50 is bigger that the number 9.50.

3 Likes

Thank you very much, with this I was able to resolve my question.

It was a great help to me.

1 Like

I agree @steevej ,

Thank you so much.

1 Like