使用用户名和密码远程连接MongoDB数据库,用Java和Scala连接其实原理相同,都是JDBC,用MongoDB的连接驱动,只是语法上稍有区别而已,而在类、方法的调用上一模一样。
在此,分享一下Scala连接MongoDB查看数据的Code,语法结构上稍作修改就可以用Java实现。
首先,下载连接驱动,添加到工程里,下载地址:mongo-java-driver-3.7.0.jar
scala代码如下
import java.io.{File, PrintWriter}
import com.mongodb.{MongoClient, ServerAddress}
import com.mongodb.client.{FindIterable, MongoCollection, MongoCursor, MongoDatabase}
import org.bson.Document
import com.mongodb.MongoCredential
import java.util.ArrayList
object MondoDBtoES {
def main(args: Array[String]): Unit = {
//初始化和连接
try {
//两个变量分别为服务器地址和端口
val serverAddress:ServerAddress = new ServerAddress("XX.XXX.XX.XX",27017)
val adds = new ArrayList[ServerAddress]()
adds.add(serverAddress)
//用户名,连接的数据库名,用户密码
val credential = MongoCredential.createCredential("user", "test","passwd".toCharArray)
val credentials = new ArrayList[MongoCredential]()
credentials.add(credential)
//通过验证连接到MongoDB客户端
val mongoClient:MongoClient = new MongoClient(adds,credentials)
//连接数据库
val mongoDatabase:MongoDatabase = mongoClient.getDatabase("test")
println("Connect MongoDB Successfully!!!")
val collection:MongoCollection[Document] = mongoDatabase.getCollection("price_discount")
println("已经选中集合price_discount")
printf(collection.count().toString)
//检索所有文档
//获取迭代器
val findInterable:FindIterable[Document] = collection.find()
//获取游标
val mongoCursor:MongoCursor[Document] = findInterable.iterator()
//开始遍历
while (mongoCursor.hasNext){
println(mongoCursor.next())
}
} catch {
case e:Exception=>
println(e.getClass.getName + ": " + e.getMessage)
}
}
}