[英]Using $sum and $avg with $addFields in MongoDB Aggregation
[英]Get average via AVG MongoDB using Lookup
我正在嘗試獲取 MongoDB 中一個集合的平均值和總和,為此我做了一個$lookup正確返回信息但是當我想對它進行分組並獲得總和以及平均值時,這兩個屬性總是將它們返回為 null
這是我的 MongoDB 查詢:
db.clients.aggregate(
[
{
$lookup: { // DATA OK
from: 'sales',
localField: '_id',
foreignField: 'clientId',
as: 'ventaPorCliente'
}
},
{
$group: { // total_average and sum null
_id: "$idClient",
username: { $first: "$name" },
total_average: { $avg: 'ventaPorCliente.total'},
sum: { $sum: 'ventaPorCliente.total'},
count: { $sum: 1 }
}
},
]
)
回復:
[
{
"_id": "1",
"username": "Peishion",
"total_average": null,
"sum": 0,
"count": 1
},
{
"_id": "1010",
"username": "BENJAMIN",
"total_average": null,
"sum": 0,
"count": 1
}
]
我如何訪問ventaporCliente.total ?
謝謝。
您錯過了$
符號,還展開了ventaPorCliente
數組,因為 $lookup 將匹配的對象推送到數組中。 嘗試這個:
db.clients.aggregate(
[
{
$lookup: {
from: 'sales',
localField: '_id',
foreignField: 'clientId',
as: 'ventaPorCliente'
}
},
{
$unwind: "$ventaPorCliente"
}
{
$group: {
_id: "$idClient",
username: { $first: "$name" },
total_average: { $avg: '$ventaPorCliente.total'},
sum: { $sum: '$ventaPorCliente.total'},
count: { $sum: 1 }
}
},
]
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.