【发布时间】:2022-01-22 01:20:56
【问题描述】:
我有 2 个收藏:
公会:
{
name: { type: String },
owner: { type: String },
discord: {
id: { type: String }
}
}
日志命令:
{
discordId: { type: String },
guild: { type: String },
name: { type: String },
}
我编写了一个函数来获取所有者的所有公会,并为每个公会计算与公会相关的日志总和。
功能:
Guild.aggregate([
{
$match: {
owner: ObjectId(userId),
},
},
{
$lookup: {
from: 'logcommands',
localField: 'discord.id',
foreignField: 'guild',
as: 'logs',
},
},
{ $addFields: { commandCount: { $size: '$logs' } } },
]);
这是可行的,但我不希望 mongoDB 检索所有相关的 logCommands(为了提高性能),我只想要每个公会的日志计数,可以在不执行连接操作的情况下获得它($lookup) ?
感谢您的帮助!
【问题讨论】:
-
如果你只需要每个公会的计数,你可以在
logCommands中做一个$group,比如{$group: {_id: "$guild", commandCount: {$sum: 1}}}