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
如果我用 (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 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
[在此處輸入圖片描述][1]
我正在嘗試將 ventas.cantidad 與 productos.precio 相乘,但由于某種原因,當我呼叫 (producto.precio) 時,它會轉換為字串 [1]:https ://i.stack.imgur.com/VqD57.png
uj5u.com熱心網友回復:
這可以解決問題:
https://mongoplayground.net/p/l4o7KFyt6Ch
在您查找 1-1 關系之后(我看到您的資料至少現在是 1-1)。您應該展開查找的結果,因為默認情況下查找會為您提供一個陣列。
理論上,展開會根據陣列中的專案數創建一個檔案。
如果您有任何問題,請告訴我
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/482018.html
上一篇:在MongoDB中按多個專案分組
