[英]Get average via AVG MongoDB using Lookup
I am trying to obtain the average and sum of totals of a collection in MongoDB, for this I do a $lookup which returns the information correctly but when I want to group it and obtain the sum of totals as well as the average, those two properties always return them as null我正在尝试获取 MongoDB 中一个集合的平均值和总和,为此我做了一个$lookup正确返回信息但是当我想对它进行分组并获得总和以及平均值时,这两个属性总是将它们返回为 null
This is my MongoDB Query:这是我的 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 }
}
},
]
)
Response:回复:
[
{
"_id": "1",
"username": "Peishion",
"total_average": null,
"sum": 0,
"count": 1
},
{
"_id": "1010",
"username": "BENJAMIN",
"total_average": null,
"sum": 0,
"count": 1
}
]
How can i access to ventaporCliente.total ?我如何访问ventaporCliente.total ?
Thanks.谢谢。
You missed the $
sign, also unwind the ventaPorCliente
array, as $lookup pushes the matching objects in an array.您错过了
$
符号,还展开了ventaPorCliente
数组,因为 $lookup 将匹配的对象推送到数组中。 Try this:尝试这个:
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.