Document

【MongoDB】5.MongoDB与java的简单结合

1.首先 你的清楚你的MongoDB的版本是多少  就下载对应的架包

下载地址如下:

http://mongodb.github.io/mongo-java-driver/  

2.新建一个项目  把架包扔进去,并Build path到你的项目下【如果用于测试,请如下 多用一个架包】

 

3.新建一个MongoConnection类 用来获取MongoDB的连接对象:

package com.mongo.util;

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 MongoConnection {

/**
* 需要验证用户名 密码的 MongoDB的连接方式 com.mongodb.MongoClient.getDatabase("数据库名")
* @return
*/
public MongoDatabase getConnection() {
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("连接成功");
return mongoDatabase;
} catch (Exception e) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
return null;
}

/**
* 不需要验证 用户名+密码 的获取连接的方式 com.mongodb.MongoClient.getDatabase("数据库名")
* @return
*/
public MongoDatabase getConnectionBasis(){
try {
//连接到mongodb服务
MongoClient mongoClient = new MongoClient("localhost",27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
System.out.println("连接成功");
return mongoDatabase;
} catch (Exception e) {
System.out.println(e.getClass().getName()+":"+e.getMessage());
}
return null;
}

}

复制代码
 1 package com.mongo.util;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import com.mongodb.MongoClient;
 7 import com.mongodb.MongoCredential;
 8 import com.mongodb.ServerAddress;
 9 import com.mongodb.client.MongoDatabase;
10 
11 public class MongoConnection {
12      
13     /**
14      * 需要验证用户名  密码的 MongoDB的连接方式   com.mongodb.MongoClient.getDatabase("数据库名")
15      * @return
16      */
17     public MongoDatabase getConnection() {
18          try {  
19                 //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址  
20                 //ServerAddress()两个参数分别为 服务器地址 和 端口  
21                 ServerAddress serverAddress = new ServerAddress("localhost",27017);  
22                 List<ServerAddress> addrs = new ArrayList<ServerAddress>();  
23                 addrs.add(serverAddress);  
24                   
25                 //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码  
26                 MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());  
27                 List<MongoCredential> credentials = new ArrayList<MongoCredential>();  
28                 credentials.add(credential);  
29                   
30                 //通过连接认证获取MongoDB连接  
31                 MongoClient mongoClient = new MongoClient(addrs,credentials);  
32                   
33                 //连接到数据库  
34                 MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");  
35                 System.out.println("连接成功");  
36                 return mongoDatabase;
37             } catch (Exception e) {  
38                 System.err.println( e.getClass().getName() + ": " + e.getMessage() );  
39             }  
40          return null;
41     }
42     
43     /**
44      * 不需要验证  用户名+密码  的获取连接的方式 com.mongodb.MongoClient.getDatabase("数据库名")
45      * @return
46      */
47     public MongoDatabase getConnectionBasis(){
48         try {
49             //连接到mongodb服务
50             MongoClient mongoClient = new MongoClient("localhost",27017);
51             MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
52             System.out.println("连接成功");
53             return mongoDatabase;
54         } catch (Exception e) {
55             System.out.println(e.getClass().getName()+":"+e.getMessage());
56         }
57         return null;
58     }
59     
60 }
复制代码

4.再建一个类 用来测试 你的增删改查

package com.mongo.test;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import org.junit.Test;

import com.mongo.util.MongoConnection;
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 MongoTest {

MongoConnection connection = new MongoConnection();
//连接到数据库
MongoDatabase mongoDatabase = connection.getConnectionBasis();


@Test
public void test(){
//createCollection();//创建 集合 一次就好
MongoCollection<Document> collection = getCollection();
insertDomcument(collection);
findAll(collection);
//delete(collection);
}

/**
* 创建 集合【对应RDBMS 中的数据表】 com.mongodb.client.MongoDatabase.createCollection("集合名")
*/
public void createCollection(){
mongoDatabase.createCollection("testConllection");
System.out.println("创建集合成功");
}

/**
* 获取 集合【对应RDBMS 中的数据表】com.mongodb.client.MongoDatabase.getCollection("集合名")
*/
public MongoCollection<Document> getCollection(){
MongoCollection<Document> collection = mongoDatabase.getCollection("testConllection");
System.out.println("转换到指定集合");
return collection;
}

/**
* 插入 文档【对应RDBMS 中的一条数据】com.mongodb.client.MongoCollection<Document>.insertOne()/insertMany()
*/
public void insertDomcument(MongoCollection<Document> collection){
/**
* 1. 创建文档 org.bson.Document 参数为key-value的格式
* 2. 创建文档集合List<Document>
* 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document)
* */
Document document = new Document();
document.append("name", "走四方");
document.append("age", 23);
document.append("url", "www.baidu.com");

List<Document> list = new ArrayList<Document>();
list.add(document);

collection.insertMany(list);
System.out.println("插入文档成功");

//插入 单条数据
Document t = new Document();
t.append("name", "走什么");
t.append("age", 26);
t.append("url", "www.agen.cn");

collection.insertOne(t);
System.out.println("插入单条数据成功");
}

/**
* 查询 所有文档【表内 数据】com.mongodb.client.MongoCollection<Document>.find()
* 查询 本条数据的时间节点 _id采用ObjectId格式
*
* ObjectId 是一个12字节 BSON 类型数据,有以下格式:
前4个字节表示时间戳
接下来的3个字节是机器标识码
紧接的两个字节由进程id组成(PID)
最后三个字节是随机数。
*/
public void findAll(MongoCollection<Document> collection){
/**
* 1. 获取迭代器FindIterable<Document>
* 2. 获取游标MongoCursor<Document>
* 3. 通过游标遍历检索出的文档集合
* */
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
Document document = mongoCursor.next();
System.out.println("MongoDB数据:"+document);
System.out.println("本地时间:"+new SimpleDateFormat().format(document.getObjectId("_id").getDate()));
}
}

/**
* 更新 所有文档【表内 数据】com.mongodb.client.MongoCollection<Document>.updateMany()
*/
public void update(MongoCollection<Document> collection){

collection.updateMany(Filters.eq("age", 26), new Document("$set",new Document("age",100)));

FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println("更新后的MongoDB数据:"+cursor.next());
}
}


/**
* 删除 文档 com.mongodb.client.MongoCollection<Document>.deleteMany()/deleteOne()
*/
public void delete(MongoCollection<Document> collection){
// 删除符合条件的 第一个文档
collection.findOneAndDelete(Filters.eq("age", 26));
//删除符合条件的 所有文档
collection.deleteMany(Filters.gte("age", 20));

FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> cursor = findIterable.iterator();
while(cursor.hasNext()){
System.out.println("删除后的MongoDB数据:"+cursor.next());
}
}
}

 

 

复制代码
  1 package com.mongo.test;
  2 
  3 
  4 import java.text.SimpleDateFormat;
  5 import java.util.ArrayList;
  6 import java.util.List;
  7 
  8 import org.bson.Document;
  9 import org.junit.Test;
 10 
 11 import com.mongo.util.MongoConnection;
 12 import com.mongodb.client.FindIterable;
 13 import com.mongodb.client.MongoCollection;
 14 import com.mongodb.client.MongoCursor;
 15 import com.mongodb.client.MongoDatabase;
 16 import com.mongodb.client.model.Filters;
 17 
 18 public class MongoTest {
 19     
 20     MongoConnection connection = new MongoConnection();
 21     //连接到数据库
 22     MongoDatabase mongoDatabase = connection.getConnectionBasis();
 23     
 24     
 25     @Test
 26     public void test(){
 27         //createCollection();//创建   集合 一次就好
 28         MongoCollection<Document> collection = getCollection();
 29         insertDomcument(collection);
 30         findAll(collection);
 31         //delete(collection);
 32     }
 33     
 34     /**
 35      * 创建  集合【对应RDBMS 中的数据表】 com.mongodb.client.MongoDatabase.createCollection("集合名")
 36      */
 37     public void createCollection(){
 38         mongoDatabase.createCollection("testConllection");
 39         System.out.println("创建集合成功");
 40     }
 41     
 42     /**
 43      * 获取  集合【对应RDBMS 中的数据表】com.mongodb.client.MongoDatabase.getCollection("集合名")
 44      */
 45     public MongoCollection<Document> getCollection(){
 46         MongoCollection<Document>  collection = mongoDatabase.getCollection("testConllection");
 47         System.out.println("转换到指定集合");
 48         return collection;
 49     }
 50     
 51     /**
 52      * 插入  文档【对应RDBMS 中的一条数据】com.mongodb.client.MongoCollection<Document>.insertOne()/insertMany()
 53      */
 54     public void insertDomcument(MongoCollection<Document> collection){
 55         /** 
 56         * 1. 创建文档 org.bson.Document 参数为key-value的格式 
 57         * 2. 创建文档集合List<Document> 
 58         * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document) 
 59         * */
 60         Document document = new Document();
 61         document.append("name", "走四方");
 62         document.append("age", 23);
 63         document.append("url", "www.baidu.com");
 64         
 65         List<Document> list = new ArrayList<Document>();
 66         list.add(document);
 67         
 68         collection.insertMany(list);
 69         System.out.println("插入文档成功");
 70         
 71         //插入 单条数据
 72         Document  t = new Document();
 73         t.append("name", "走什么");
 74         t.append("age", 26);
 75         t.append("url", "www.agen.cn");
 76         
 77         collection.insertOne(t);
 78         System.out.println("插入单条数据成功");
 79     }
 80     
 81     /**
 82      * 查询  所有文档【表内 数据】com.mongodb.client.MongoCollection<Document>.find()
 83      * 查询  本条数据的时间节点   _id采用ObjectId格式
 84      * 
 85      * ObjectId 是一个12字节 BSON 类型数据,有以下格式:
 86             前4个字节表示时间戳
 87             接下来的3个字节是机器标识码
 88             紧接的两个字节由进程id组成(PID)
 89             最后三个字节是随机数。
 90      */
 91     public void findAll(MongoCollection<Document> collection){
 92         /** 
 93         * 1. 获取迭代器FindIterable<Document> 
 94         * 2. 获取游标MongoCursor<Document> 
 95         * 3. 通过游标遍历检索出的文档集合 
 96         * */
 97          FindIterable<Document> findIterable = collection.find();
 98          MongoCursor<Document> mongoCursor = findIterable.iterator();
 99          while(mongoCursor.hasNext()){
100              Document document = mongoCursor.next();
101              System.out.println("MongoDB数据:"+document);
102              System.out.println("本地时间:"+new SimpleDateFormat().format(document.getObjectId("_id").getDate()));
103          }
104     }
105     
106     /**
107      * 更新   所有文档【表内  数据】com.mongodb.client.MongoCollection<Document>.updateMany()
108      */
109     public void update(MongoCollection<Document> collection){
110         
111         collection.updateMany(Filters.eq("age", 26), new Document("$set",new Document("age",100)));
112         
113         FindIterable<Document> findIterable = collection.find();
114         MongoCursor<Document> cursor = findIterable.iterator();
115         while (cursor.hasNext()) {
116             System.out.println("更新后的MongoDB数据:"+cursor.next());
117         }
118     }
119     
120     
121     /**
122      * 删除  文档 com.mongodb.client.MongoCollection<Document>.deleteMany()/deleteOne()
123      */
124     public void delete(MongoCollection<Document> collection){
125         // 删除符合条件的 第一个文档
126         collection.findOneAndDelete(Filters.eq("age", 26));
127         //删除符合条件的  所有文档
128         collection.deleteMany(Filters.gte("age", 20));
129         
130         FindIterable<Document> findIterable = collection.find();
131         MongoCursor<Document> cursor = findIterable.iterator();
132         while(cursor.hasNext()){
133             System.out.println("删除后的MongoDB数据:"+cursor.next());
134         }
135     }
136     
137     
138     
139     
140     
141 }
复制代码
posted @ 2018-03-22 12:49  从未被超越  阅读(288)  评论(0编辑  收藏  举报