如何在 mongodb 中将字符串转换为 int

How to convert a string to int in mongodb

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 onError 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

如果我用 (toInt) 这样做,它会告诉我这个

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 onError 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

[在此处输入图片描述][1]

我正在尝试将 ventas.cantidad 与 productos.precio 相乘,但是 出于某种原因,当我调用 (producto.precio) 它转换为字符串 [1]: https://i.stack.imgur.com/VqD57.png

这样做就可以了:

https://mongoplayground.net/p/l4o7KFyt6Ch

查找 1-1 关系后(我看到你的数据至少目前是 1-1)。您应该展开查找的结果,因为默认情况下查找会为您提供一个数组。

理论上,unwind 根据数组中的项目数创建一个文档。

如果您有任何问题,请告诉我