【问题标题】:MongoDB countDocuments() very slow in Scala as compared to MongoDB Compass与 MongoDB Compass 相比,Scala 中的 MongoDB countDocuments() 非常慢
【发布时间】:2020-04-27 00:41:24
【问题描述】:

我正在尝试让 MongoDB 根据 where 子句对文档进行计数

  def headResult(): C = Await.result(observable.head(), Duration(10, TimeUnit.SECONDS))

  val database: MongoDatabase = mongoClient.getDatabase("dbname")
  val collection: MongoCollection[Document] = database.getCollection("tablename")
  val recordCount = collection.countDocuments()
            .headResult() 

此查询返回计数为 766 782,但需要 2-2.5 秒。当我通过 MongoDB Compass 进行相同的查询时,需要 0.2 秒。

  db.tbltrackerdata.find({},{}).count()

由于 where 子句是动态的,我无法为此保存或维护任何元数据。

【问题讨论】:

  • 所以它不是同一个查询。您是否尝试在 MongoDB Compass 中添加相同的过滤器并查看需要多长时间?他们可能没有被索引
  • 是的,我的过滤器保持不变... Compass 的响应速度非常快,但仅使用 Scala 驱动程序需要一些时间。我不知道如何以及为什么
  • 但是您在指南针查询中显示了一个空过滤器?
  • 所以我更新了我的问题。另外,我怀疑是不是因为 Scala ,它很慢。在某个地方,我看到 scala 中的游标在使用 golang 代码时相对较慢。这可能吗?

标签: mongodb scala mongoose mongodb-query


【解决方案1】:

这不是因为 Scala。这是因为db.collection.count({})db.collection.find({}).count() 实际上并没有获取文档。相反,它只是从集合的元数据中检索文档的数量。

countDocuments 方法执行适当的聚合,预计会更慢但也更准确。您可以在此处的 MongoDB 文档中看到它: https://docs.mongodb.com/manual/reference/method/db.collection.countDocuments/#mechanics

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2017-05-07
    • 1970-01-01
    • 2016-07-13
    相关资源
    最近更新 更多