我有两个集合,并尝试在两个不同的条件下求和。
Heere是我的代码:
db.drivers.aggregate([
{
$lookup: {
from: "bookings",
let: { driver_id: "$_id" },
pipeline: [
{ $match: { $expr: { $eq: ["$driverId", "$$driver_id"] } } },
{
$group: {
_id: "$driverId",
totalAmount: { $sum: "$driverAmount" }
}
}
],
as: "bookingdata",
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ["$driverId", "$$driver_id"] },
{ $eq: ["$payment.settled", false] }
]
}
}
},
{
$group: {
_id: "$driverId",
totaldues: { $sum: "$driverAmount" }
},
bookingdata: {
$push: "$totaldues"
}
},
{ $project: { _id: 0, totalAmount: 1, totaldues: 1 } }
]
}
}
]);
它得出的是总额或应付款,但不是全部。如何获取司机详细信息以及总额和应缴的总金额?
答案 0 :(得分:1)
您不能在同一对象中多次使用同一字段,就像在这里使用pipeline
一样。
请改为在$facet
内部使用$lookup
聚合来一次处理多个管道。
db.drivers.aggregate([
{ "$lookup": {
"from": "bookings",
"let": { "driver_id": "$_id" },
"pipeline": [
{ "$facet": {
"totaldues": [
{ "$match": {
"$expr": {
"$and": [
{ "$eq": ["$driverId", "$$driver_id"] },
{ "$eq": ["$payment.settled", false] }
]
}
}},
{ "$group": {
"_id": "$driverId",
"totaldues": { "$sum": "$driverAmount" },
"bookingdata": { "$push": "$totaldues" }
}},
{ "$project": { "_id": 0, "totalAmount": 1, "totaldues": 1 } }
],
"totalAmount": [
{ "$match": { "$expr": { "$eq": ["$driverId", "$$driver_id"] } }},
{ "$group": {
"_id": "$driverId",
"totalAmount": { "$sum": "$driverAmount" }
}}
]
}}
],
"as": "bookingdata"
}}
])