使用Lookup通过AVG MongoDB获取平均值

xzlaal3s  于 2022-11-22  发布在  Go
关注(0)|答案(1)|浏览(162)

我试图获得MongoDB中集合的平均值和总和,为此我做了一个**$lookup**,它正确地返回信息,但当我想对它进行分组并获得总和和平均值时,这两个属性总是返回空值
这是我的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

  • 谢谢-谢谢
1tu0hz3e

1tu0hz3e1#

你错过了$符号,也解开了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 }
            }
        },
    ]
)

相关问题