Mongoose:$project return 中的 $sum 只有零
Mongoose: $sum in $project return only zero
我有一个查询使用 $lookup that "join" two models and $project to select all fields that i need only, and in that $project I need to $sum 一个名为 totalValue
的值,但只有 return 零:
我的查询
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
}
},
您需要 $project
user_details
投影中的 value
字段才能在下一个聚合阶段获得它
{ "$project": { "scheduleStart": 1, "scheduleEnd": 1, "value": 1 }}
我有一个查询使用 $lookup that "join" two models and $project to select all fields that i need only, and in that $project I need to $sum 一个名为 totalValue
的值,但只有 return 零:
我的查询
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
}
},
您需要 $project
user_details
投影中的 value
字段才能在下一个聚合阶段获得它
{ "$project": { "scheduleStart": 1, "scheduleEnd": 1, "value": 1 }}