MongoDB Java 连接配置
【前言】
由于处于线程安全等考虑,MongoDBJava从3.0开始已经打算废弃DB开头的类的使用,所以整体调用上有了较大的区别,特以此文志之
【正文】
环境配置
在Java程序中如果要使用MongoDB,你需要确保已经安装了Java环境及MongoDB JDBC 驱动。
· 首先你必须下载mongo jar包,
Git下载地址:https://github.com/mongodb/mongo-java-driver/downloads,
国内快速下载地址:http://central.maven.org/maven2/org/mongodb/mongo-java-driver/
网盘下载地址:http://pan.baidu.com/s/1i3Mv0dn (这里测试使用3.2.2版)。
· 你需要将mongo.jar包含在你的 classpath中
连接数据库
连接数据库,你需要指定数据库名称,如果指定的数据库不存在,mongo会自动创建数据库。
连接数据库的Java代码如下:
- import java.util.ArrayList;
- import java.util.List;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.MongoDatabase;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
- System.out.println("Connect to database successfully");
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
创建集合
我们可以使用com.mongodb.client.MongoDatabase类中的createCollection()来创建集合
代码片段如下:
- import java.util.ArrayList;
- import java.util.List;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.MongoDatabase;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
- System.out.println("Connect to database successfully");
- //创建集合 参数为 “集合名称”
- mongoDatabase.createCollection("collectionName");
- System.out.println("Collection created successfully");
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
获取集合
我们可以使用com.mongodb.DBCollection类的 getCollection()方法来获取一个集合
代码片段如下:
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoDatabase;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
- System.out.println("Connect to database successfully");
- //获取集合 参数为“集合名称”
- MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
- System.out.println("Collection mycol selected successfully");
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
插入文档
我们可以使用com.mongodb.client.MongoCollection类的insert()方法来插入一个文档
代码片段如下:
- import java.util.ArrayList;
- import java.util.List;
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoDatabase;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
- System.out.println("Connect to database successfully");
- //获取集合 参数为“集合名称”
- MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
- System.out.println("Collection mycol selected successfully");
- //插入文档
- /**
- * 1. 创建文档 org.bson.Document 参数为key-value的格式
- * 2. 创建文档集合List<Document>
- * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document)
- * */
- Document document = new Document("title", "MongoDB").
- append("description", "database").
- append("likes", 100).
- append("by", "Fly");
- List<Document> documents = new ArrayList<Document>();
- documents.add(document);
- mongoCollection.insertMany(documents);
- System.out.println("Document inserted successfully");
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
检索所有文档
我们可以使用com.mongodb.client.MongoCollection类中的find()方法来获取集合中的所有文档。
此方法返回一个游标,所以你需要遍历这个游标。
代码片段如下:
- import java.util.ArrayList;
- import java.util.List;
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.FindIterable;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoCursor;
- import com.mongodb.client.MongoDatabase;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
- System.out.println("Connect to database successfully");
- //获取集合 参数为“集合名称”
- MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
- System.out.println("Collection mycol selected successfully");
- //检索所有文档
- /**
- * 1. 获取迭代器FindIterable<Document>
- * 2. 获取游标MongoCursor<Document>
- * 3. 通过游标遍历检索出的文档集合
- * */
- FindIterable<Document> findIterable = mongoCollection.find();
- MongoCursor<Document> mongoCursor = findIterable.iterator();
- while(mongoCursor.hasNext()){
- System.out.println(mongoCursor.next());
- }
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
更新文档
你可以使用com.mongodb.client.MongoCollection类中的 updateOne()或updateMany()方法来更新集合中的文档。
代码片段如下:
- import java.util.ArrayList;
- import java.util.List;
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.FindIterable;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoCursor;
- import com.mongodb.client.MongoDatabase;
- import com.mongodb.client.model.Filters;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("userName", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
- System.out.println("Connect to database successfully");
- //获取集合 参数为“集合名称”
- MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
- System.out.println("Collection mycol selected successfully");
- //更新文档 将文档中likes=100的文档修改为likes=200
- mongoCollection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));
- //检索查看结果
- FindIterable<Document> findIterable = mongoCollection.find();
- MongoCursor<Document> mongoCursor = findIterable.iterator();
- while(mongoCursor.hasNext()){
- System.out.println(mongoCursor.next());
- }
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
删除文档
要删除集合中符合条件的文档,需要使用com.mongodb.client.MongoCollection类中的deleteOne ()或deleteMany()方法。分别表示删除第一个符合条件的文档和删除所有符合条件的文档。
代码片段如下:
- import java.util.ArrayList;
- import java.util.List;
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.FindIterable;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoCursor;
- import com.mongodb.client.MongoDatabase;
- import com.mongodb.client.model.Filters;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("userName", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("<span style="font-family: Arial, Helvetica, sans-serif;">databaseName</span><span style="font-family: Arial, Helvetica, sans-serif;">");</span>
- System.out.println("Connect to database successfully");
- //获取集合 参数为“集合名称”
- MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
- System.out.println("Collection mycol selected successfully");
- //删除符合条件的第一个文档
- mongoCollection.deleteOne(Filters.eq("likes", 200));
- //删除所有符合条件的文档
- mongoCollection.deleteMany (Filters.eq("likes", 200));
- //检索查看结果
- FindIterable<Document> findIterable = mongoCollection.find();
- MongoCursor<Document> mongoCursor = findIterable.iterator();
- while(mongoCursor.hasNext()){
- System.out.println(mongoCursor.next());
- }
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
要注意,上面的数据库连接我都没有手动调用关闭,为了防止意外发生建议加上如下代码:
- finally{
- mongoClient.close();
- }
你还可以使用aggregate(),createIndex(),count()等方法来操作MongoDB数据库、集合。
MongoDB Java 连接配置的更多相关文章
- MongoDB Java连接---MongoDB基础用法(四)
MongoDB 连接 标准 URI 连接语法: mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN ...
- mongodb远程连接配置
mongodb远程连接配置如下: 1.修改配置文件mongodb.conf 命令:vim /etc/mongodb.conf 把 bind_ip=127.0.0.1 这一行注释掉或者是修改成 bind ...
- oracle java连接配置
oracle数据库连接使用ojdbc驱动.使用tomcat-jdbc连接池. pom.xml: <!-- tomcat jdbc --> <dependency> <gr ...
- Mongodb集群搭建及spring和java连接配置记录
一.基本环境: mongdb3.0.5数据库 spring-data-mongodb-1.7.2.jar mongo-java-driver-3.0.2.jar linux-redhat6.3 tom ...
- MongoDB Java
MongoDB Java 环境配置 在Java程序中如果要使用MongoDB,你需要确保已经安装了Java环境及MongoDB JDBC 驱动. 你可以参考本站的Java教程来安装Java程序.现在让 ...
- mongodb在Windows安装配置及遇到的问题、java连接测试
一.安装 1.访问mongodb的官网http://www.mongodb.org/downloads下载64bit的包,我下载的是mongodb-win32-x86_64-2008plus-ssl- ...
- java mongodb连接配置实践——生产环境最优
之前百度,google了很多,发现并没有介绍mongodb生产环境如何配置的文章, 当时想参考下都不行, 所以写篇文章,大家可以一块讨论下. 1. MongoClientOptions中的连接池配置: ...
- Java连接MongoDB进行增删改查
1.导入必须的包: 详情看项目:http://pan.baidu.com/s/1cvDAOY 2.通过Myeclipse创建WEB项目 3. 3.bean:创建实体类 package com.bean ...
- Mongodb Java Driver 参数配置解析
要正确使用Mongodb Java Driver,MongoClientOptions参数配置对数据库访问的并发性能影响极大. connectionsPerHost:与目标数据库能够建立的最大conn ...
随机推荐
- PLSQL常用时间函数
body { font-family: "Microsoft YaHei UI","Microsoft YaHei",SimSun,"Segoe UI ...
- C++的函数重载 转
——每个现象后面都隐藏一个本质,关键在于我们是否去挖掘 写在前面: 函数重载的重要性不言而明,但是你知道C++中函数重载是如何实现的呢(虽然本文谈的是C++中函数重载的实现,但我想其它语言也是类似的) ...
- 24种设计模式--抽象工厂模式【Abstract Factory Pattern】
女娲造人,人是造出来了,世界是热闹了,可是低头一看,都是清一色的类型,缺少关爱.仇恨.喜怒哀乐等情绪,人类的生命太平淡了,女娲一想,猛然一拍脑袋,忘记给人类定义性别了,那怎么办?抹掉重来,然后就把人类 ...
- 理解Php中的Static
① 使用 static 可以将类中的成员标识为静态的,既可以用来标识成员属性,也可以用来标识成员方法,比如: <?php class China { public static $boy = 1 ...
- 工欲善其事必先利其器-Notepad++使用小记(Python)
大学开始就一直使用Notepad++ 作为代码编辑器,喜欢它的简洁明了,喜欢它的个性,也喜欢它各种各样骚气的插件. 今天闲来无事,写篇文章记录一下平时使用的种种,包括但不限于个性化使用一些宏,快捷键, ...
- C#委托(Delegate)学习日记
在.NET平台下,委托类型用来定义和响应应用程序中的回调.事实上,.NET委托类型是一个类型安全的对象,指向可以以后调用的其他方法.和传统的C++函数指针不同,.NET委托是内置支持多路广播和异步方法 ...
- Contest20140705 testB DP
testB 输入文件: testB.in 输出文件testB.out 时限2000ms 问题描述: 方师傅有两个由数字组成的串 a1,a2,⋯,an 和 b1,b2,⋯,bm.有一天,方师傅感到十分无 ...
- OpenJDK与HashMap
OpenJDK的非堆JDK增强提议(JDK Enhancement-Proposal,JEP)试图标准化一项基础设施,它从Java6开始,只能在HotSpot和OpenJDK内部使用.这种设施能够像管 ...
- 关于 width;height
IE Firefox Chrome Safari window(width|height) no yes yes document.body document.documentElement 网页 ...
- 自定义JSON配置器
比如要写个专门处理float类型的方法,然后注册到JSON配置器中,具体如下: 配置器代码如下: import java.math.RoundingMode; import java.text.Num ...