【问题标题】:MongoDb : count documents in other collection without a join operationMongoDb:在没有连接操作的情况下计算其他集合中的文档
【发布时间】: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}}}

标签: mongodb join


【解决方案1】:

查询

  • 您可以使用管道查找,查找结果只有计数
  • 波纹管需要 MongoDB 5,localfield 和 foreignfield 与您的查找相同,除了小管道只是为了计数
  • 查找后,$set 是要稍微改变结构。

Test code here

Guild.aggregate(
[{"$match":{"owner":1}},
 {"$lookup":
  {"from":"logcommands",
   "localField":"discord.id",
   "foreignField":"guild",
   "pipeline":[{"$count":"count"}],
   "as":"logs"}},
 {"$set":{"logs":{"$arrayElemAt":["$logs.count", 0]}}}])

【讨论】:

  • 非常感谢!你知道你的聚合是否比我的更快吗?我正在努力获取聚合的执行时间
  • 像你一样工作,只是不要用文档构建大数组,为了更快,你可以在 foreignFiled guild 上创建索引
  • on owner 也做索引,会超快的
猜你喜欢
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 2017-06-14
  • 1970-01-01
  • 2021-03-20
  • 1970-01-01
  • 2015-07-20
  • 2019-09-04
相关资源
最近更新 更多