我有 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)的情況下獲得它?
謝謝你的幫助 !
uj5u.com熱心網友回復:
詢問
- 您可以使用帶有管道的查找,并且查找結果只有計數
- 波紋管需要 MongoDB 5,localfield 和 foreignfield 與您的查找相同,除了用于計數的小管道
- 查找之后,
$set就是稍微改變一下結構。
測驗代碼在這里
Guild.aggregate(
[{"$match":{"owner":1}},
{"$lookup":
{"from":"logcommands",
"localField":"discord.id",
"foreignField":"guild",
"pipeline":[{"$count":"count"}],
"as":"logs"}},
{"$set":{"logs":{"$arrayElemAt":["$logs.count", 0]}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/387990.html
