Mat*_*eus 2 mongoose mongodb node.js mongodb-query aggregation-framework
我有这个查询,并且正在使用$lookup,之后我想对value查找提供的数组中的求和。
我的查询(我正在使用猫鼬):
User.aggregate([{
$match: {
storeKey: req.body.store,
}
},
{
$group: {
_id: {
id: "$_id",
name: "$name",
cpf: "$cpf",
phone: "$phone",
email: "$email",
birthday: "$birthday"
},
totalServices: {
$sum: "$services"
}
}
},
{
$lookup: {
from: "schedules",
localField: "_id.phone",
foreignField: "customer.phone",
as: "user_detail"
}
},
{ $project: { "user_detail.value": 1 } },
])
Run Code Online (Sandbox Code Playgroud)
我的查询结果(样本集合):
{
"_id": {
"id": "5bd89899bda5c343749d00f0",
"name": "marcio",
"cpf": null,
"phone": "11999999999",
"email": "marcio@gmail.com",
"birthday": "2018-10-30T17:44:57.834Z"
},
"user_detail": [
{
"value": 50
},
{
"value": 50
},
{
"value": 40
},
{
"value": 20
},
{
"value": 20
},
{
"value": 50
},
{
"value": 18
},
{
"value": 20
},
{
"value": 20
},
{
"value": 10
},
{
"value": 120
},
{
"value": 50
},
{
"value": 120
},
{
"value": 20
},
{
"value": 20
},
{
"value": 25
},
{
"value": 20
},
{
"value": 20
},
{
"value": 20
},
{
"value": 10
},
{
"value": 20
},
{
"value": 20
},
{
"value": 35
},
{
"value": 20
},
{
"value": 20
}
]
}
Run Code Online (Sandbox Code Playgroud)
如何将所有字段相加value并显示该总和的结果与我的第一个 $group 的结果?
您可以 $sum对数组值使用聚合
db.user.aggregate([
// $group stage
{ "$lookup": {
"from": "schedule",
"localField": "_id.phone",
"foreignField": "customer.phone",
"as": "user_detail"
}},
{ "$project": {
"total": { "$sum": "$user_detail.value" }
}}
])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3862 次 |
| 最近记录: |