database - 将数组内的不同数量的值相乘:Mongodb
问题描述
我已经安排了我的数据,以便将属于同一客户 ID 的文档聚合到一个集合中。数据格式如下。
{
"items": [
{
"stock_code": [
"22617",
"22768",
"20749"
],
"description": [
"DESIGN",
"FAMILY PHOTO FRAME",
"ASSORTED CASES"
],
"quantity": [
18,
12,
84
],
"unit_price": [
4.95,
9.95,
6.35
]
}
],
"_id": 581485,
"customer_id": 17389,
"country": "United Kingdom"
}
我需要将数组数量的值与相应的 unit_price 相乘,并获得一个新字段中多个文档的总数。我曾尝试使用 $reduce 函数和 $map 函数来获取输出,但它们都导致“错误”
乘法只支持数值类型,不支持数组
你能否建议我应该如何去完成这个。
代码尝试:
"$addFields": {"order_total" :
{
"$sum": {
"$map": {
"input": "$items",
"as": "items",
"in": { "$multiply": [
{ "$ifNull": [ "$$items.quantity", 0 ] },
{ "$ifNull": [ "$$items.unit_price", 0 ] }
]}
}
}
}
}
第二:
"order_total" : {
"$reduce" : {
"input" : "$items",
"initialValue" : Decimal128("0.00"),
"in": {
"$sum" : [
"$$value",
{"$multiply" : [ "$$this.quantity", "$$this.unit_price" ] }
]}
}
}
预期的结果需要通过将unit_price的对应条目乘以数量来添加一个新的“total”字段。错误消息是multiply 仅支持数字类型而不支持数组。
解决方案
试试下面的查询:
db.collection.aggregate(
[{ $unwind: { path: "$items",} },
{ $unwind: { path: "$items.quantity",} },
{ $unwind: { path: "$items.unit_price",} },
{ $addFields: { 'total': {$multiply: ["$items.quantity", "$items.unit_price"] }} }])
推荐阅读
- powershell - 为什么带通配符的get-childitem不好用?
- r - 在 Mac 上更改 R 版本的 shell
- c# - 如何在 C# 中使用 IP 地址在热敏打印机(80 毫米)中打印 RDLC 报告
- csv - Lua - 从 .csv 文件中删除空白行行或在处理时跳过它们?
- sql - ASP.NET Core Identity User 如何使用外键引用自动更新表
- c# - Wix 配置文件中的 ExcelDna 集成
- javascript - 清除间隔不起作用。问题是什么?我该如何解决?
- javascript - 如何使用 fetch() 获得的 vanilla JS 每 x 秒更新一次信息?
- ios - 同时拖入 UIView 和 Collection View
- java - 如何从 Flutter 插件启动主应用程序的 MainActivity