设为首页 收藏本站
查看: 792|回复: 0

[经验分享] MongoDB Java 连接配置

[复制链接]

尚未签到

发表于 2017-12-15 09:35:48 | 显示全部楼层 |阅读模式
  【前言】
  由于处于线程安全等考虑,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包含在你的>连接数据库
  连接数据库,你需要指定数据库名称,如果指定的数据库不存在,mongo会自动创建数据库。
  连接数据库的Java代码如下:
[java] view plain copy

  • 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()来创建集合
  代码片段如下:
[java] view plain copy

  • 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()方法来获取一个集合

  代码片段如下:
[java] view plain copy

  • 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()方法来插入一个文档
  代码片段如下:
[java] view plain copy

  • 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()方法来获取集合中的所有文档。
  此方法返回一个游标,所以你需要遍历这个游标。
  代码片段如下:
[java] view plain copy

  • 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()方法来更新集合中的文档。
  代码片段如下:
[java] view plain copy

  • 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()方法。分别表示删除第一个符合条件的文档和删除所有符合条件的文档。
  代码片段如下:
[java] view plain copy

  • 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() );
  •         }
  •     }
  • }
  要注意,上面的数据库连接我都没有手动调用关闭,为了防止意外发生建议加上如下代码:
[java] view plain copy

  • finally{
  •     mongoClient.close();
  • }
  你还可以使用aggregate(),createIndex(),count()等方法来操作MongoDB数据库、集合。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-424267-1-1.html 上篇帖子: Ubuntu14.04下初步使用MongoDB 下篇帖子: MongoDB 复制篇
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表