简体   繁体   English

如何使用 MongoDb Scala 驱动程序进行同步查询

[英]How to make synchronous queries using MongoDb Scala driver

As "MongoDb Scala Driver" is the only official Scala driver now, I plan to switch from Casbah.由于“MongoDb Scala Driver”是现在唯一的官方Scala驱动程序,我打算从Casbah切换。 However, MongoDb Scala Driver seems to support only Asynchronous API (at least in its documentation).但是,MongoDb Scala Driver 似乎只支持异步 API(至少在其文档中)。 Is there a way to make synchronous queries?有没有办法进行同步查询?

I had the same problems some days ago when I was moving from Casbah.几天前我从卡斯巴搬来时也遇到了同样的问题。 Apparently the official Mongodb driver uses the observer pattern.显然,官方的 Mongodb 驱动程序使用观察者模式。 I wanted to retrieve a sequence number from a collection and I had to wait for the value to be retrieved to continue the operation.我想从集合中检索序列号,我必须等待检索到的值才能继续操作。 I am not sure if that's the correct way, but at least this is one way of doing it:我不确定这是否是正确的方法,但至少这是一种方法:

def getSequenceId(seqName: String): Int = {

  val query = new BsonDocument("seq_id", new BsonString(seqName))    
  val resultado = NewMongo.SequenceCollection.findOneAndUpdate(query,inc("nextId",1))    
  resultado.subscribe(new Observer[Document] {        
    override def onNext(result: Document): Unit ={}
    override def onError(e: Throwable): Unit ={}
    override def onComplete(): Unit = {}
  })
  val awaitedR = Await.result(resultado.toFuture, Duration.Inf).asInstanceOf[List[Document]](0)

  val ret = awaitedR.get("nextId").getOrElse(0).asInstanceOf[BsonDouble].intValue();

  return ret;  
}

Apparently you can convert the result observer into a future and wait for its return using the Await function as I did.显然,您可以像我一样使用 Await 函数将结果观察者转换为未来并等待其返回。 Then you can manipulate the result as you wish.然后您可以根据需要操作结果。

The database configuration is the following:数据库配置如下:

private val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/?maxPoolSize=30")
private val database: MongoDatabase = mongoClient.getDatabase("mydb");
val Sequence: MongoCollection[Document] = database.getCollection(SEQUENCE);

Hope my answer was helpful希望我的回答有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM