我正在构建一个游戏应用程序,其数据库在Mongodb中。我有一个为玩家设定等级的模型。
const mongoose = require('mongoose');
// Ranks Schema -- Sub Schema of ContestsType
const rankSchema = mongoose.Schema({
rank:{
type: Number,
required: true
},
pAmt:{
type: Number,
required: true
}
});
// ContestsType Schema
const ContestsTypeSchema = mongoose.Schema({
contestTypeName:{
type: String,
required: true
},
noOfWinners:{
type: Number,
required: true
},
ranks : [rankSchema]
});这是上述模式的示例数据:
{
"_id" : ObjectId("5a83e99e64b803361cd82e7c"),
"noOfWinners" : 15.0,
"ranks" : [
{
"rank" : 1.0,
"pAmt" : 1000.0
},
{
"rank" : 2.0,
"pAmt" : 500.0
},
{
"rank" : 3.0,
"pAmt" : 50.0
},
{
"rank" : 4.0,
"pAmt" : 50.0
},
{
"rank" : 5.0,
"pAmt" : 50.0
},
{
"rank" : 6.0,
"pAmt" : 25.0
},
{
"rank" : 7.0,
"pAmt" : 25.0
},
{
"rank" : 8.0,
"pAmt" : 25.0
},
{
"rank" : 9.0,
"pAmt" : 25.0
},
{
"rank" : 10.0,
"pAmt" : 25.0
}
],
"contestTypeName" : "20 Teams | 15 Winners",
}正如你所看到的,我有等级,我想把它们分成几个等级,比如等级1是1000,等级2是500,而等级3-5是50。
因此,我想以范围格式向用户显示等级,即
Rank 1 : 1000
Rank 2 : 500
Rank 3-5 : 50
Rank 5-10 : 25 这是我写的Mongo聚合管道。
db.contestTypes.aggregate(
// Pipeline
[
// Stage 1
{
$match: {
_id : ObjectId("5a83e99e64b803361cd82e7c"),
}
},
// Stage 2
{
$unwind: {
path : "$ranks",
}
},
// Stage 3
{
$group: {
_id : "$ranks.pAmt"
}
},
]);
这至少给了我以下的结果

发布于 2018-04-10 09:16:22
您可以使用MongoDB 3.4中引入的聚合阶段。
这使您可以根据boundaries中定义的范围对数据进行分组。
首先,使用$unwind展开数组,然后应用$bucket:
db.collection.aggregate([{
"$unwind": "$ranks"
},
{
"$bucket": {
"groupBy": "$ranks.rank",
"boundaries": [1, 2, 5, 10, 15],
"default": 0,
"output": {
"pAmt": {
"$first": "$ranks.pAmt"
}
}
}
}
])这一产出:
[
{
"_id": 1,
"pAmt": 1000
},
{
"_id": 2,
"pAmt": 500
},
{
"_id": 5,
"pAmt": 50
},
{
"_id": 10,
"pAmt": 25
}
]你可以在这里试试:Mongoplayplace.net/p/v3ZoV8bhlVS
https://stackoverflow.com/questions/49748725
复制相似问题