mongodb - 如何有效地检查 Scala 的 MongoDB 集合是否为空?
问题描述
我想检查 MongoDB 集合是否为空。
我知道这种方法有效:
if (client.getDatabase(dbName).getCollection(collectionName) == 0)
使用这种方法,我正在计算整个集合。花费的时间是昂贵的。还有另一种更省时的方法吗?
解决方案
原始问题中发布的代码不会检查集合是否为空。它将一个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
推荐阅读
- c++ - CPP 使用不存在的密钥访问地图
- c# - 运行 devenv 来构建 VDPROJ 设置
- python-3.x - 如何在 pyspark 数据框列上应用功能
- android - 如何在具有不同对象类型的 Room 中创建可流动的交易?
- sql - 查找工资率的最新日期
- gcc - 在 Fedora 31 上交叉编译时找不到 crt1.o
- javascript - Javascript中定义的对象的未定义引用错误
- apache-camel - AMQP 消费者在第 127 条消息时停止接收
- java - 使用 android studio 将文本框数据发送到在线网站文本框(POST 数据和 GET 数据)
- windows - 如何通过 sstp-client 路由并非所有流量