首页 > 解决方案 > 如何有效地检查 Scala 的 MongoDB 集合是否为空?

问题描述

我想检查 MongoDB 集合是否为空。

我知道这种方法有效:

if (client.getDatabase(dbName).getCollection(collectionName) == 0)

使用这种方法,我正在计算整个集合。花费的时间是昂贵的。还有另一种更省时的方法吗?

标签: mongodbscala

解决方案


原始问题中发布的代码不会检查集合是否为空。它将一个MongoCollection对象与一个进行比较Int,在这种情况下,该语句将始终评估为false。重新创建逻辑会导致以下警告消息:

warning: comparing values of types org.mongodb.scala.MongoCollection[org.mongodb.scala.bson.collection.immutable.Document] and Int using `==' will always yield false

我过去曾使用过以下模式,尽管我不确定这是否是最有效或最标准的方法(尤其是因为它使用var了 Scala 的禁忌):

/* countDocuments() replaces deprecated count() in org.mongodb.scala 2.4
 * https://mongodb.github.io/mongo-scala-driver/2.4/scaladoc/org/mongodb/scala/MongoCollection.html 
 * https://mongodb.github.io/mongo-scala-driver/2.4/changelog/
 */

var isEmpty = true // your result will be stored here
var processing = true
val collection = client.getDatabase(dbName).getCollection(collectionName)
collection.countDocuments().subscribe((cnt: Long) => {
   isEmpty = (cnt == 0)
   processing = false
})
while(processing) {} // wait here until async call is completed

推荐阅读