当前位置: 首页 > 工具软件 > Jongo > 使用案例 >

scala jongo操作mongodb

越福
2023-12-01

依赖


libraryDependencies += "org.jongo" % "jongo" % "1.5.0"

libraryDependencies += "org.mongodb" % "mongo-java-driver" % "3.11.3"

模型

由于我们是用的java的驱动,并非scala系列的驱动,所以用普通class,非case class

class Session {
  var _id: ObjectId = _
  var user_id: String = _
  var auth_token: String = _
 
  var updated_at: Date = _
  var created_at: Date = _
  var deleted_at: Date = _

 	// 部分字段省略

}

查询

val client = new MongoClient()
val db = client.getDB("你的db名称")
val jongo = new Jongo(db)
val collection = jongo.getCollection("session")
val begin = 1488010173
val end = 1488011459
val raw = {
  s"""
  {
    $$match:{
    create_time:{
    $$gt:$begin
    }
    }
    },{
    $$match:{
    create_time:{
    $$lt:$end
    }
    }
  }
"""
}

val result = collection.aggregate(raw).as(classOf[Session])
while (result.hasNext) {
  println(result.next())
}
 类似资料: