我有一个查询,使用$lookup“联接”两个模型,然后使用$project选择我只需要的所有字段,在那个$project中,我需要$sum名为totalValue
的值,但仅返回零:
我的查询
User.aggregate([{
$match: {
storeKey: req.body.store,
}
},
{
$group: {
_id: {
id: "$_id",
name: "$name",
cpf: "$cpf",
phone: "$phone",
email: "$email",
birthday: "$birthday",
lastName: "$lastname"
},
totalServices: {
$sum: "$services"
},
}
},
{
$lookup: {
from: "schedules",
"let": { "id": "$_id.phone" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$customer.phone", "$$id"] }}},
{ "$project": { "scheduleStart": 1, "scheduleEnd": 1 }}
],
"as": "user_detail"
}
},
{
$project: {
_id: 1,
name: 1,
name: 1,
cpf: 1,
phone: 1,
email: 1,
birthday: 1,
totalServices: 1,
totalValue: { $sum : "$user_detail.value" }, // here only return zero
count: {
$sum: 1
},
user_detail: 1
}
},
答案 0 :(得分:1)
您需要在value
投影中$project
user_details
字段中进行下一聚合阶段
{ "$project": { "scheduleStart": 1, "scheduleEnd": 1, "value": 1 }}