在 MongoDB 聚合框架中,我希望在地圖上使用 $unwind 運算子。看起來是不可能的。
case class MatchStatus(
totalRows: Int,
fullMatch: Int,
noMatch: Int,
partialMatch: Int
)
這是我有 matchStatus => Map<String,MatchStatus> 的示例 JSON
{
"_id" : ObjectId("61e8c7bbd0597207179faa89"),
"clientId" : "DEMO",
"matchStatus" : {
"summary" : {
"totalRows" : "10",
"fullMatch" : "5",
"noMatch" : "1",
"partialMatch" : "4"
},
"income" : {
"totalRows" : "10",
"fullMatch" : "1",
"noMatch" : "0",
"partialMatch" : "1"
}
},
"date" : "18-01-2022"
},
{
"_id" : ObjectId("61e8c7bbd0597207179faa89"),
"clientId" : "DEMO-1",
"sizes" : [
"1",
"2"
],
"matchStatus" : {
"summary" : {
"totalRows" : "10",
"fullMatch" : "5",
"noMatch" : "1",
"partialMatch" : "4"
},
"income" : {
"totalRows" : "10",
"fullMatch" : "1",
"noMatch" : "0",
"partialMatch" : "1"
},
"slip" : {
"totalRows" : "10",
"fullMatch" : "1",
"noMatch" : "0",
"partialMatch" : "1"
},
},
"date" : "18-01-2022"
}
所以我想要的輸出是=>
{
"summary":{
"totalRows" : "20",
"fullMatch" : "10",
"noMatch" : "2",
"partialMatch" : "8"
},
"income":{
"totalRows" : "20",
"fullMatch" : "10",
"noMatch" : "0",
"partialMatch" : "2"
},
"slip":{
"totalRows" : "10",
"fullMatch" : "1",
"noMatch" : "0",
"partialMatch" : "1"
}
}
或者與此類似的東西,我獲取密鑰(摘要、收入、單據)并匯總值。
嘗試了 $unwind 但在地圖結構上不起作用。
uj5u.com熱心網友回復:
也許有一個較小的聚合
db.collection.aggregate([
{
"$match": {
"_id": {
"$in": [
ObjectId("61e8c7bbd0597207179faa89"),
ObjectId("61e8c7bbd0597207179faa90")
]
}
}
},
{
"$set": {
"matchStatus": {
$objectToArray: "$matchStatus"
}
}
},
{
"$unwind": "$matchStatus"
},
{
"$replaceRoot": {
"newRoot": "$matchStatus"
}
},
{
"$set": {
"v": {
$objectToArray: "$v"
}
}
},
{
"$unwind": "$v"
},
{
"$group": {
"_id": {
k1: "$k",
k2: "$v.k"
},
"sum": {
"$sum": {
"$toInt": "$v.v"
}
}
}
},
{
"$group": {
"_id": "$_id.k1",
"field": {
"$push": {
k: "$$ROOT._id.k2",
v: "$$ROOT.sum"
}
}
}
},
{
"$project": {
"v": {
$arrayToObject: "$field"
}
}
},
{
"$group": {
"_id": null,
"field": {
"$push": {
k: "$$ROOT._id",
v: "$$ROOT.v"
}
}
}
},
{
"$replaceRoot": {
"newRoot": {
$arrayToObject: "$field"
}
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/418498.html
標籤:
