Home > Back-end >  How to convert a string to int in mongodb
How to convert a string to int in mongodb

Time:05-28

db.productos.find()
{ "_id" : 1, "nombre" : "Camisa", "precio" : 5 }
{ "_id" : 2, "nombre" : "Saco", "precio" : 10 }
db.ventas.find()
{ "_id" : 1, "articulo" : 1, "cantidad" : 10 }
{ "_id" : 2, "articulo" : 2, "cantidad" : 25 }

db.ventas.aggregate([
  {
    $lookup:{from: "productos", localField: "articulo",
     foreignField: "_id", as: "producto"}
  }, 
  {
    $project: {
      _id: 0, nombre: "$producto.nombre", cantidad: 1,
      precio_unidad: "$producto.precio", 
      precio_total: {$multiply: 
        ["$cantidad", {$convert: {input: "$producto.precio", to:"int"}}]
      }
    }
  }
])
2022-05-26T16:40:41.077-0500 E QUERY    [js] Error: command failed: {
        "ok" : 0,
        "errmsg" : "Unsupported conversion from array to int in $convert with no one rror value",
        "code" : 241,
        "codeName" : "ConversionFailure"
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:601:17
assert.commandWorked@src/mongo/shell/assert.js:694:16
DB.prototype._runAggregate@src/mongo/shell/db.js:262:9
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1074:12
@(shell):1:1

if I do it with (toInt) it tells me this

db.ventas.aggregate([
   {
    $lookup:{from: "productos", localField: "articulo", foreignField: 
    "_id", as: "producto"}
   }, 
   {
    $project: {_id: 0, nombre: "$producto.nombre", cantidad: 1, 
    precio_unidad: "$producto.precio", precio_total: {$multiply: 
     ["$cantidad", {$toInt: '$producto.precio'}]
   }
  }
 }
])
2022-05-27T12:05:50.074-0500 E QUERY    [js] Error: command failed: {
        "ok" : 0,
        "errmsg" : "Unsupported conversion from array to int in $convert with no one rror value",
        "code" : 241,
        "codeName" : "ConversionFailure"
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:601:17
assert.commandWorked@src/mongo/shell/assert.js:694:16
DB.prototype._runAggregate@src/mongo/shell/db.js:262:9
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1074:12
@(shell):1:1

[enter image description here][1]

I'm trying to multiply ventas.cantidad with productos.precio but for some reason when i call (producto.precio) it converts to a string [1]: https://i.stack.imgur.com/VqD57.png

CodePudding user response:

This will do the trick:

https://mongoplayground.net/p/l4o7KFyt6Ch

After you do a lookup into a 1-1 relationship (as I see your data at least for now is a 1-1). You should unwind the result of the lookup because by default the lookup gives you an array.

In theory, the unwind creates a document per number of items you have in an array.

Let me know if you have questions

  • Related