【前言】

由于处于线程安全等考虑,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代码如下:

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import com.mongodb.MongoClient;
  4. import com.mongodb.MongoCredential;
  5. import com.mongodb.ServerAddress;
  6. import com.mongodb.client.MongoDatabase;
  7. public class MongoDBJDBC {
  8. public static void main(String[] args){
  9. try {
  10. //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
  11. //ServerAddress()两个参数分别为 服务器地址 和 端口
  12. ServerAddress serverAddress = new ServerAddress("localhost",27017);
  13. List<ServerAddress> addrs = new ArrayList<ServerAddress>();
  14. addrs.add(serverAddress);
  15. //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
  16. MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
  17. List<MongoCredential> credentials = new ArrayList<MongoCredential>();
  18. credentials.add(credential);
  19. //通过连接认证获取MongoDB连接
  20. MongoClient mongoClient = new MongoClient(addrs,credentials);
  21. //连接到数据库
  22. MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
  23. System.out.println("Connect to database successfully");
  24. } catch (Exception e) {
  25. System.err.println( e.getClass().getName() + ": " + e.getMessage() );
  26. }
  27. }
  28. }

创建集合

我们可以使用com.mongodb.client.MongoDatabase类中的createCollection()来创建集合

代码片段如下:

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import com.mongodb.MongoClient;
  4. import com.mongodb.MongoCredential;
  5. import com.mongodb.ServerAddress;
  6. import com.mongodb.client.MongoDatabase;
  7. public class MongoDBJDBC {
  8. public static void main(String[] args){
  9. try {
  10. //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
  11. //ServerAddress()两个参数分别为 服务器地址 和 端口
  12. ServerAddress serverAddress = new ServerAddress("localhost",27017);
  13. List<ServerAddress> addrs = new ArrayList<ServerAddress>();
  14. addrs.add(serverAddress);
  15. //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
  16. MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
  17. List<MongoCredential> credentials = new ArrayList<MongoCredential>();
  18. credentials.add(credential);
  19. //通过连接认证获取MongoDB连接
  20. MongoClient mongoClient = new MongoClient(addrs,credentials);
  21. //连接到数据库
  22. MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
  23. System.out.println("Connect to database successfully");
  24. //创建集合 参数为 “集合名称”
  25. mongoDatabase.createCollection("collectionName");
  26. System.out.println("Collection created successfully");
  27. } catch (Exception e) {
  28. System.err.println( e.getClass().getName() + ": " + e.getMessage() );
  29. }
  30. }
  31. }

获取集合

我们可以使用com.mongodb.DBCollection类的 getCollection()方法来获取一个集合

代码片段如下:

  1. import org.bson.Document;
  2. import com.mongodb.MongoClient;
  3. import com.mongodb.MongoCredential;
  4. import com.mongodb.ServerAddress;
  5. import com.mongodb.client.MongoCollection;
  6. import com.mongodb.client.MongoDatabase;
  7. public class MongoDBJDBC {
  8. public static void main(String[] args){
  9. try {
  10. //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
  11. //ServerAddress()两个参数分别为 服务器地址 和 端口
  12. ServerAddress serverAddress = new ServerAddress("localhost",27017);
  13. List<ServerAddress> addrs = new ArrayList<ServerAddress>();
  14. addrs.add(serverAddress);
  15. //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
  16. MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
  17. List<MongoCredential> credentials = new ArrayList<MongoCredential>();
  18. credentials.add(credential);
  19. //通过连接认证获取MongoDB连接
  20. MongoClient mongoClient = new MongoClient(addrs,credentials);
  21. //连接到数据库
  22. MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
  23. System.out.println("Connect to database successfully");
  24. //获取集合 参数为“集合名称”
  25. MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
  26. System.out.println("Collection mycol selected successfully");
  27. } catch (Exception e) {
  28. System.err.println( e.getClass().getName() + ": " + e.getMessage() );
  29. }
  30. }
  31. }

插入文档

我们可以使用com.mongodb.client.MongoCollection类的insert()方法来插入一个文档

代码片段如下:

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import org.bson.Document;
  4. import com.mongodb.MongoClient;
  5. import com.mongodb.MongoCredential;
  6. import com.mongodb.ServerAddress;
  7. import com.mongodb.client.MongoCollection;
  8. import com.mongodb.client.MongoDatabase;
  9. public class MongoDBJDBC {
  10. public static void main(String[] args){
  11. try {
  12. //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
  13. //ServerAddress()两个参数分别为 服务器地址 和 端口
  14. ServerAddress serverAddress = new ServerAddress("localhost",27017);
  15. List<ServerAddress> addrs = new ArrayList<ServerAddress>();
  16. addrs.add(serverAddress);
  17. //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
  18. MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
  19. List<MongoCredential> credentials = new ArrayList<MongoCredential>();
  20. credentials.add(credential);
  21. //通过连接认证获取MongoDB连接
  22. MongoClient mongoClient = new MongoClient(addrs,credentials);
  23. //连接到数据库
  24. MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
  25. System.out.println("Connect to database successfully");
  26. //获取集合 参数为“集合名称”
  27. MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
  28. System.out.println("Collection mycol selected successfully");
  29. //插入文档
  30. /**
  31. * 1. 创建文档 org.bson.Document 参数为key-value的格式
  32. * 2. 创建文档集合List<Document>
  33. * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document)
  34. * */
  35. Document document = new Document("title", "MongoDB").
  36. append("description", "database").
  37. append("likes", 100).
  38. append("by", "Fly");
  39. List<Document> documents = new ArrayList<Document>();
  40. documents.add(document);
  41. mongoCollection.insertMany(documents);
  42. System.out.println("Document inserted successfully");
  43. } catch (Exception e) {
  44. System.err.println( e.getClass().getName() + ": " + e.getMessage() );
  45. }
  46. }
  47. }

检索所有文档

我们可以使用com.mongodb.client.MongoCollection类中的find()方法来获取集合中的所有文档。

此方法返回一个游标,所以你需要遍历这个游标。

代码片段如下:

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import org.bson.Document;
  4. import com.mongodb.MongoClient;
  5. import com.mongodb.MongoCredential;
  6. import com.mongodb.ServerAddress;
  7. import com.mongodb.client.FindIterable;
  8. import com.mongodb.client.MongoCollection;
  9. import com.mongodb.client.MongoCursor;
  10. import com.mongodb.client.MongoDatabase;
  11. public class MongoDBJDBC {
  12. public static void main(String[] args){
  13. try {
  14. //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
  15. //ServerAddress()两个参数分别为 服务器地址 和 端口
  16. ServerAddress serverAddress = new ServerAddress("localhost",27017);
  17. List<ServerAddress> addrs = new ArrayList<ServerAddress>();
  18. addrs.add(serverAddress);
  19. //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
  20. MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
  21. List<MongoCredential> credentials = new ArrayList<MongoCredential>();
  22. credentials.add(credential);
  23. //通过连接认证获取MongoDB连接
  24. MongoClient mongoClient = new MongoClient(addrs,credentials);
  25. //连接到数据库
  26. MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
  27. System.out.println("Connect to database successfully");
  28. //获取集合 参数为“集合名称”
  29. MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
  30. System.out.println("Collection mycol selected successfully");
  31. //检索所有文档
  32. /**
  33. * 1. 获取迭代器FindIterable<Document>
  34. * 2. 获取游标MongoCursor<Document>
  35. * 3. 通过游标遍历检索出的文档集合
  36. * */
  37. FindIterable<Document> findIterable = mongoCollection.find();
  38. MongoCursor<Document> mongoCursor = findIterable.iterator();
  39. while(mongoCursor.hasNext()){
  40. System.out.println(mongoCursor.next());
  41. }
  42. } catch (Exception e) {
  43. System.err.println( e.getClass().getName() + ": " + e.getMessage() );
  44. }
  45. }
  46. }

更新文档

你可以使用com.mongodb.client.MongoCollection类中的 updateOne()或updateMany()方法来更新集合中的文档。

代码片段如下:

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import org.bson.Document;
  4. import com.mongodb.MongoClient;
  5. import com.mongodb.MongoCredential;
  6. import com.mongodb.ServerAddress;
  7. import com.mongodb.client.FindIterable;
  8. import com.mongodb.client.MongoCollection;
  9. import com.mongodb.client.MongoCursor;
  10. import com.mongodb.client.MongoDatabase;
  11. import com.mongodb.client.model.Filters;
  12. public class MongoDBJDBC {
  13. public static void main(String[] args){
  14. try {
  15. //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
  16. //ServerAddress()两个参数分别为 服务器地址 和 端口
  17. ServerAddress serverAddress = new ServerAddress("localhost",27017);
  18. List<ServerAddress> addrs = new ArrayList<ServerAddress>();
  19. addrs.add(serverAddress);
  20. //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
  21. MongoCredential credential = MongoCredential.createScramSha1Credential("userName", "databaseName", "password".toCharArray());
  22. List<MongoCredential> credentials = new ArrayList<MongoCredential>();
  23. credentials.add(credential);
  24. //通过连接认证获取MongoDB连接
  25. MongoClient mongoClient = new MongoClient(addrs,credentials);
  26. //连接到数据库
  27. MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
  28. System.out.println("Connect to database successfully");
  29. //获取集合 参数为“集合名称”
  30. MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
  31. System.out.println("Collection mycol selected successfully");
  32. //更新文档   将文档中likes=100的文档修改为likes=200
  33. mongoCollection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));
  34. //检索查看结果
  35. FindIterable<Document> findIterable = mongoCollection.find();
  36. MongoCursor<Document> mongoCursor = findIterable.iterator();
  37. while(mongoCursor.hasNext()){
  38. System.out.println(mongoCursor.next());
  39. }
  40. } catch (Exception e) {
  41. System.err.println( e.getClass().getName() + ": " + e.getMessage() );
  42. }
  43. }
  44. }

删除文档

要删除集合中符合条件的文档,需要使用com.mongodb.client.MongoCollection类中的deleteOne ()或deleteMany()方法。分别表示删除第一个符合条件的文档和删除所有符合条件的文档。

代码片段如下:

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import org.bson.Document;
  4. import com.mongodb.MongoClient;
  5. import com.mongodb.MongoCredential;
  6. import com.mongodb.ServerAddress;
  7. import com.mongodb.client.FindIterable;
  8. import com.mongodb.client.MongoCollection;
  9. import com.mongodb.client.MongoCursor;
  10. import com.mongodb.client.MongoDatabase;
  11. import com.mongodb.client.model.Filters;
  12. public class MongoDBJDBC {
  13. public static void main(String[] args){
  14. try {
  15. //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
  16. //ServerAddress()两个参数分别为 服务器地址 和 端口
  17. ServerAddress serverAddress = new ServerAddress("localhost",27017);
  18. List<ServerAddress> addrs = new ArrayList<ServerAddress>();
  19. addrs.add(serverAddress);
  20. //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
  21. MongoCredential credential = MongoCredential.createScramSha1Credential("userName", "databaseName", "password".toCharArray());
  22. List<MongoCredential> credentials = new ArrayList<MongoCredential>();
  23. credentials.add(credential);
  24. //通过连接认证获取MongoDB连接
  25. MongoClient mongoClient = new MongoClient(addrs,credentials);
  26. //连接到数据库
  27. MongoDatabase mongoDatabase = mongoClient.getDatabase("<span style="font-family: Arial, Helvetica, sans-serif;">databaseName</span><span style="font-family: Arial, Helvetica, sans-serif;">");</span>
  28. System.out.println("Connect to database successfully");
  29. //获取集合 参数为“集合名称”
  30. MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
  31. System.out.println("Collection mycol selected successfully");
  32. //删除符合条件的第一个文档
  33. mongoCollection.deleteOne(Filters.eq("likes", 200));
  34. //删除所有符合条件的文档
  35. mongoCollection.deleteMany (Filters.eq("likes", 200));
  36. //检索查看结果
  37. FindIterable<Document> findIterable = mongoCollection.find();
  38. MongoCursor<Document> mongoCursor = findIterable.iterator();
  39. while(mongoCursor.hasNext()){
  40. System.out.println(mongoCursor.next());
  41. }
  42. } catch (Exception e) {
  43. System.err.println( e.getClass().getName() + ": " + e.getMessage() );
  44. }
  45. }
  46. }

要注意,上面的数据库连接我都没有手动调用关闭,为了防止意外发生建议加上如下代码:

  1. finally{
  2. mongoClient.close();
  3. }

你还可以使用aggregate(),createIndex(),count()等方法来操作MongoDB数据库、集合。

MongoDB Java 连接配置的更多相关文章

  1. MongoDB Java连接---MongoDB基础用法(四)

    MongoDB 连接 标准 URI 连接语法: mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN ...

  2. mongodb远程连接配置

    mongodb远程连接配置如下: 1.修改配置文件mongodb.conf 命令:vim /etc/mongodb.conf 把 bind_ip=127.0.0.1 这一行注释掉或者是修改成 bind ...

  3. oracle java连接配置

    oracle数据库连接使用ojdbc驱动.使用tomcat-jdbc连接池. pom.xml: <!-- tomcat jdbc --> <dependency> <gr ...

  4. Mongodb集群搭建及spring和java连接配置记录

    一.基本环境: mongdb3.0.5数据库 spring-data-mongodb-1.7.2.jar mongo-java-driver-3.0.2.jar linux-redhat6.3 tom ...

  5. MongoDB Java

    MongoDB Java 环境配置 在Java程序中如果要使用MongoDB,你需要确保已经安装了Java环境及MongoDB JDBC 驱动. 你可以参考本站的Java教程来安装Java程序.现在让 ...

  6. mongodb在Windows安装配置及遇到的问题、java连接测试

    一.安装 1.访问mongodb的官网http://www.mongodb.org/downloads下载64bit的包,我下载的是mongodb-win32-x86_64-2008plus-ssl- ...

  7. java mongodb连接配置实践——生产环境最优

    之前百度,google了很多,发现并没有介绍mongodb生产环境如何配置的文章, 当时想参考下都不行, 所以写篇文章,大家可以一块讨论下. 1. MongoClientOptions中的连接池配置: ...

  8. Java连接MongoDB进行增删改查

    1.导入必须的包: 详情看项目:http://pan.baidu.com/s/1cvDAOY 2.通过Myeclipse创建WEB项目 3. 3.bean:创建实体类 package com.bean ...

  9. Mongodb Java Driver 参数配置解析

    要正确使用Mongodb Java Driver,MongoClientOptions参数配置对数据库访问的并发性能影响极大. connectionsPerHost:与目标数据库能够建立的最大conn ...

随机推荐

  1. Python:对象

    #!/usr/bin/python3 #对象实例 class Person: num=200 def __init__(self,name,sex): self.name=name self.sex= ...

  2. 24种设计模式--抽象工厂模式【Abstract Factory Pattern】

    女娲造人,人是造出来了,世界是热闹了,可是低头一看,都是清一色的类型,缺少关爱.仇恨.喜怒哀乐等情绪,人类的生命太平淡了,女娲一想,猛然一拍脑袋,忘记给人类定义性别了,那怎么办?抹掉重来,然后就把人类 ...

  3. Java学习----有风险的代码(异常)

    Exception继承了Throwable,但是它本身是有异常类的父类. RuntimeException:运行时异常 Exception->RuntimeException->NullP ...

  4. ubuntu14.04 开启root登陆

    想要在登录界面使用root身份登录,可编辑/usr/share/lightdm/lightdm.conf.d/50-ubuntu.conf文件, sudo gedit /usr/share/light ...

  5. Cloudera Impala 之 ORDER BY without LIMIT currently not supported

    ERROR: NotImplementedException: ORDER BY without LIMIT currently not supported   impala中order by 需要l ...

  6. Docker安装Gitlab

    一.Ubuntu16.4上Docker安装Gitlab 1.安装docker 参见:https://docs.docker.com/engine/installation/linux/ubuntuli ...

  7. IOC(控制反转)与DI(依赖注入)的个人理解。

    控制反转IOC(Inversion of Control)的三个需要理清问题: 1.谁控制了谁,控制了什么东西?IOC容器控制了依赖对象的创建. 2.谁得到了反转? 一般的应用程序是,直接创建依赖于该 ...

  8. [译]36 Days of Web Testing(一)

    [前言]最近负责的一次迭代发布中,一个小需求涉及前端JS改动,在测试这个需求的过程中忽略了浏览器兼容性测试,导致了一个线上bug.恶补下web测试,<36Days of web testing& ...

  9. BASLER 镜头选型白皮书

    本文翻译自Basler镜头选型白皮书 有许多方法来进行镜头选型.本文将会讨论其中的指导原则,以帮助你在项目中选择合适的镜头.我们将讨论许多镜头的基本概念,比如镜头接口.图像大小.放大率.焦距.F数和光 ...

  10. Hibernate中的一对多关系详解(2)

    一对多的关系:例如,部门对员工,一个部门可以有多个员工 多对一的关系:例如,员工对部门,多个员工属于一个部门,并且每个员工只能属于一个部门 那么一对多.多对一在数据库中的是怎样表示的呢?好多话都不说了 ...