下面是我的MongoDB文档的一个例子。 并在从产品文档中选择交易August
时,175
sum
每个交易文档中的产品数量
products
文件中的预期结果
[
{
"_id":"61012014f7416b0a41db7055",
"name":"MIE",
"retailPrice":20000,
"qtyInTransaction":175
}
]
这是我的文件
products
文档
[
{
"_id":"61012014f7416b0a41db7055",
"name":"MIE",
"retailPrice":20000,
"description":"PRODUK BARU",
}
]
producutInTransaction
文档
[
{
"_id":"6106a3b1f1bbd62640c7b404",
"transactionDate":{"$date":"2021-08-01T00:00:00.000Z"},
"productsInTransactions":
[
{
"_id":"6106a3cff1bbd62640c7b405",
"productId":"61012014f7416b0a41db7055"},
"qty":100,
"price":5000,
"description":"asdn"
},
{
"_id":"6106a3cff1bbd62640c7b406",
"productId":"61012014f7416b0a41db7055"},
"qty":50,
"price":5000,
"description":"asdn"
}
]
},
{
"_id":"6106a3b1f1bbd62640c7b4007",
"transactionDate":{"$date":"2021-08-01T00:00:00.000Z"},
"productsInTransactions":
[
{
"_id":"6106a3cff1bbd62640c7b407",
"productId":"61012014f7416b0a41db7055"},
"qty":25,
"price":5000,
"description":"asdn"
},
]
}
]
感谢您的任何帮助,对不起我的英语
您可以使用此查询(在所需的任何内容上添加ISODate
值):
- 首先按
transactionData
$match
,该必须"大于或等于"所需日期。在这里,您必须使用 JS 计算日期并使用变量。 - 然后
$unwind
productsInTransactions
字段来解构数组。 $group
productId
并$sum
qty
值。- 稍后,
$lookup
"联接"与"产品"集合,并生成具有所需值data
字段。 - 并且至少
$project
仅显示所需的字段。
db.productInTransaction.aggregate([
{
"$match": {
"transactionDate": {
"$gte": ISODate("2021-07-01T00:00:00.000Z")
}
}
},
{
"$unwind": "$productsInTransactions"
},
{
"$group": {
"_id": "$productsInTransactions.productId",
"qty": {
"$sum": "$productsInTransactions.qty"
}
}
},
{
"$lookup": {
"from": "product",
"localField": "_id",
"foreignField": "_id",
"as": "data"
}
},
{
"$project": {
"name": {
"$arrayElemAt": [
"$data.name",
0
]
},
"retailPrice": {
"$arrayElemAt": [
"$data.retailPrice",
0
]
},
"qtyInTransaction": "$qty"
}
}
])
这里的例子
结果是:
[
{
"_id": "61012014f7416b0a41db7055",
"name": "MIE",
"qtyInTransaction": 175,
"retailPrice": 20000
}
]