1 回答
TA贡献1898条经验 获得超8个赞
$set
_levelDetails
:通过转换LevelDetails
为键值对来添加新字段。$unwind
: 解构_levelDetails
数组。$group
: 分组_levelDetails.v.userId
并$sum
有条件地基于级别 (_levelDetails.k
)。$project
: 格式化显示的文件。$sort
(可选):按userID
升序排序。
db.collection.aggregate([
{
$set: {
_levelDetails: {
$objectToArray: "$LevelDetails"
}
}
},
{
$unwind: "$_levelDetails"
},
{
$group: {
_id: "$_levelDetails.v.userId",
"TotalLevel1Amount": {
$sum: {
$cond: [
{
"$eq": [
"$_levelDetails.k",
"level1"
]
},
"$_levelDetails.v.amount",
0
]
}
},
"TotalLevel2Amount": {
$sum: {
$cond: [
{
"$eq": [
"$_levelDetails.k",
"level2"
]
},
"$_levelDetails.v.amount",
0
]
}
},
"TotalLevel3Amount": {
$sum: {
$cond: [
{
"$eq": [
"$_levelDetails.k",
"level3"
]
},
"$_levelDetails.v.amount",
0
]
}
}
}
},
{
$project: {
_id: 0,
userId: "$_id",
TotalLevel1Amount: 1,
TotalLevel2Amount: 1,
TotalLevel3Amount: 1
}
},
{
$sort: {
userId: 1
}
}
])
对于键值对:
{ 'userId': { // Result } }
步骤 1 到 3 与前面的解决方案相同。
$sort
(可选):按_id
升序排序。$project
:显示带有array
字段的文档(带有属性k
和v
)。$replaceRoot
:将整个文档替换为键(userId
)和值(结果)。
db.collection.aggregate([
{
$set: {
_levelDetails: {
$objectToArray: "$LevelDetails"
}
}
},
{
$unwind: "$_levelDetails"
},
{
$group: {
_id: "$_levelDetails.v.userId",
"TotalLevel1Amount": {
$sum: {
$cond: [
{
"$eq": [
"$_levelDetails.k",
"level1"
]
},
"$_levelDetails.v.amount",
0
]
}
},
"TotalLevel2Amount": {
$sum: {
$cond: [
{
"$eq": [
"$_levelDetails.k",
"level2"
]
},
"$_levelDetails.v.amount",
0
]
}
},
"TotalLevel3Amount": {
$sum: {
$cond: [
{
"$eq": [
"$_levelDetails.k",
"level3"
]
},
"$_levelDetails.v.amount",
0
]
}
}
}
},
{
$sort: {
_id: 1
}
},
{
$project: {
array: [
{
k: {
$toString: "$_id"
},
v: {
TotalLevel1Amount: "$TotalLevel1Amount",
TotalLevel2Amount: "$TotalLevel2Amount",
TotalLevel3Amount: "$TotalLevel3Amount"
}
}
]
}
},
{
"$replaceRoot": {
newRoot: {
$arrayToObject: "$array"
}
}
}
])
- 1 回答
- 0 关注
- 125 浏览
添加回答
举报