【发布时间】:2020-09-02 06:05:07
【问题描述】:
我试图在 mongo 中对大约 40k 个对象进行排序,我有两个集合,一个是漫画,另一个是角色,角色在里面有一个字段,其中包含一系列漫画 ID。我想要的是一个聚合框架的管道,它检索具有最强角色的漫画(每个角色的强度总和)。我能够获得包含每个角色力量总和的漫画列表,但是当我尝试对其进行排序时,数据库一直在等待,一切都以超时结束。我究竟做错了什么?
字符模型:
{
_id: number,
name: string,
info: {
alignment: string // can be "good" or "bad"
}
stats: {
strength: number
},
comics: [] //array of numbers referencing the id of the comic
}
漫画模型:
{
_id: number,
name: string
}
这里是我的查询:
db.comics.aggregation(
{
$lookup: {
from: 'characters',
let: {
comic_id: '$_id',
},
as: 'total_comic_str',
pipeline: [
{
$match: {
$expr: {
$and: [
{$in: ['$$comic_id', '$comics']}, // the character is from this comic
{$eq: ['$info.alignment', 'good']} // the character is a hero
]
}
}
},
{
$group: { // group by comic id and accumulate strength of each hero
_id: '$$comic_id',
str: {
$sum: '$stats.strength'
}
}
}
]
}
},
{
$unwind: {
path: '$total_comic_str',
preserveNullAndEmptyArrays: false
}
},
{
$sort: {
'total_comic_str.str': -1
}
},
{
$limit: 1
}
)
【问题讨论】:
标签: arrays mongodb mongodb-query aggregation-framework