我想在管道的第一階段構建一個 $match 的 MongoDB 查詢,然后回傳一個物件物件,其中第一個物件是幾個常見欄位的 $project,下一個物件是不常見欄位的總和聚合,這些欄位將在管道中提及。例如,在匹配管道之后給定 2 個檔案 -
{
"bus": "EXAMP",
"city": "Kanpur",
"AccountName": "Examp Transport Service",
"agencyName": "BBS",
"depotName": "RAYAPUR HUBLI",
"CashCollection": 8,
"Collection": 30,
"IssueTicket": 5,
"PassengerCount": 4,
"TicketCount": 4
}
{
"bus": "EXAMP",
"city": "Kanpur",
"AccountName": "Examp Transport Service",
"agencyName": "BBS",
"depotName": "RAYAPUR HUBLI",
"CashCollection": 10,
"Collection": 20,
"IssueTicket": 7,
"PassengerCount": 5,
"TicketCount": 4
}
因此,我需要在第一個物件中投影欄位 [bus、city、AccountName、agencyName、depotName],而在下一個物件中,我需要聚合欄位 [CashCollection、Collection、IssueTicket、PassengerCount、TicketCount]。所以我的物件應該如下所示
{
result: [
{
"bus": "EXAMP",
"city": "Kanpur",
"AccountName": "Examp Transport Service",
"agencyName": "BBS",
"depotName": "RAYAPUR HUBLI",
}
],
aggregates: {
"CashCollection": 18,
"Collection": 50,
"IssueTicket": 12,
"PassengerCount": 9,
"TicketCount": 8
}
}
uj5u.com熱心網友回復:
您可以使用以下聚合
$match
過濾匹配的輸出。$or
如果您需要多個匹配的輸出,您可以使用$facet
分配傳入的資料$group
按匹配的欄位分組
這是代碼,
db.collection.aggregate([
{ "$match": { bus: "EXAMP" } },
{
"$facet": {
"result": [
{
"$group": {
"_id": "$bus",
"bus": { "$first": "$bus" },
"city": { "$first": "$city" },
"AccountName": { "$first": "$AccountName" },
"agencyName": { "$first": "$agencyName" },
"depotName": { "$first": "$depotName" }
}
}
],
aggregate: [
{
"$group": {
"_id": null,
"totalCollection": { $sum: "$Collection" },
"IssueTicket": { $sum: "$IssueTicket" },
"PassengerCount": { $sum: "$PassengerCount" },
"TicketCount": { $sum: "$TicketCount" }
}
}
]
}
},
{
$set: {
aggregate: {
"$ifNull": [
{ "$arrayElemAt": [ "$aggregate", 0 ] }, null ]
}
}
}
])
作業Mongo游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/494466.html