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 ...
随机推荐
- 学会怎样使用Jsp 内置标签、jstl标签库及自定义标签
学习jsp不得不学习jsp标签,一般来说,对于一个jsp开发者,可以理解为jsp页面中出现的java代码越少,对jsp的掌握就越好,而替换掉java代码的重要方式就是使用jsp标签. jsp标签的分 ...
- 343. Integer Break -- Avota
问题描述: Given a positive integer n, break it into the sum of at least two positive integers and maximi ...
- 用3种方法在 operator= 中处理“自我赋值”
假设你建立一个class 用来保存一个指针指向一块动态分配的位图. class Bitmap {......}; class Widget{ ... private: Bitmap* pb ; }; ...
- ACM Sdut 2158 Hello World!(数学题,排序) (山东省ACM第一届省赛C题)
题目描述 We know thatIvan gives Saya three problems to solve (Problem F), and this is the firstproblem. ...
- fedora安装sublime text教程
下载 http://pan.baidu.com/s/1eRkEegM 解压 终端中切换到下载文件的目录下,执行以下命令: sudo tar -jxvf sublime_text_3_build_308 ...
- PHP 面向对对象基础(接口,类)
介绍PHP面向对象的基础知识 1. 接口的定义interface ,类定义class,类支持abstract和final修饰符,abstract修饰为抽象类,抽象类 不支持直接实例化,final修饰的 ...
- linux shell获取时间
获得当天的日期 date +%Y-%m-%d 输出: 2011-07-28 将当前日期赋值给DATE变量DATE=$(date +%Y%m%d) 有时候我们需要使用今天之前或者往后的日期,这时可以使用 ...
- 新年之际,盘点一些APP开发技巧
(原文:Reader Submissions - New Year's 2015 作者:Mattt Thompson 译者:培子 校对:蓝魂) 回顾过去一年发生在我们身边的事情时,有一点不得不提:对苹 ...
- webkit.net使用方法日记
1.首先貌似只有36位的库,所以项目也要修改为X86平台 2.里面的所有dll库文件都要拷贝到项目中去,包括WebKitBrowser.dll.manifest 此文件一定要拷贝过去. 3.然后引用 ...
- UFLDL教程(六)之栈式自编码器
第0步:初始化一些参数和常数 第1步:利用训练样本集训练第一个稀疏编码器 第2步:利用训练样本集训练第二个稀疏编码器 第3步:利用第二个稀疏编码器提取到的特征训练softmax回归模型 ...