【发布时间】:2021-12-14 01:18:22
【问题描述】:
由于超时错误,我一直在努力完成聚合过程,并且没有任何在线解决方案对我有用。我通过match尽可能减少了工作量
Mongo 版本:4.1.3 使用 MongoDB 免费层
尝试:
return this.abyssBattleModel
.aggregate([
{
$match: {
floor_level: floorLevel,
battle_index: battleIndex,
},
},
{
$lookup: {
from: 'playercharacters',
localField: 'party',
foreignField: '_id',
as: 'party',
},
},
{
$project: {
_id: 0,
party: {
$map: {
input: '$party',
as: 'pc',
in: '$$pc.character',
},
},
floor_level: 1,
battle_index: 1,
star: 1,
},
},
{
$match: {
party: { $all: characterIds },
},
},
{
$group: {
_id: {
party: '$party',
floorLevel: '$floor_level',
battleIndex: '$battle_index',
},
count: {
$sum: 1,
},
avgStar: {
$avg: '$star',
},
winCount: {
$sum: {
$cond: { if: { $eq: ['$star', 3] }, then: 1, else: 0 },
},
},
},
},
{
$sort: {
count: -1,
},
},
{
$limit: limit,
},
])
.option({ maxTimeMS: 21600000, allowDiskUse: true, noCursorTimeout: true })
.exec();
在此查询中,字段party 是PlayerCharacter ObjectIds 的数组。 PlayerCharacter 对象有一个字段 character,它引用了 Character ObjectId。在此查询中,我使用$lookup 将party 更改为PlayerCharacter ObjectIds 到Character ObjectIds 的数组,以便我可以通过Character ObjectIds 过滤它们。
模型
// Filtered by floor_level and battle_index and party
// Party is an array of PlayerCharacter ObjectId
// which need to be joined with Character model to filter by Character id
export class AbyssBattle {
@Field(() => String)
_id: MongooseSchema.Types.ObjectId;
@Field(() => String)
@Prop({ required: true })
floor_level: string;
@Field(() => Number)
@Prop({ required: true })
battle_index: number;
@Field(() => Number)
@Prop({ required: true })
star: number;
@Field(() => [String])
@Prop({
type: [MongooseSchema.Types.ObjectId],
ref: 'PlayerCharacter',
required: true,
})
party: MongooseSchema.Types.ObjectId[];
}
export class PlayerCharacter {
@Field(() => String)
_id: MongooseSchema.Types.ObjectId;
@Field(() => String)
@Prop({
type: MongooseSchema.Types.ObjectId,
ref: 'Character',
required: true,
})
character: MongooseSchema.Types.ObjectId;
}
是否有另一种方法来增加超时,或者这是我不知道的 MongoDB 免费层的限制?这纯粹是一个优化问题吗?提前谢谢你。
【问题讨论】:
-
你的索引是什么?
-
你不需要
party: {$map: ...},只需使用party: "$party.character" -
抱歉,更新了帖子中的模型和其他详细信息。
-
尝试使用
explain运行查询,这可能有助于确定哪个部分较慢。
标签: mongodb mongoose aggregation-framework