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

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介: 1.首先 你的清楚你的MongoDB的版本是多少  就下载对应的架包下载地址如下:http://mongodb.github.io/mongo-java-driver/  2.新建一个项目  把架包扔进去,并Build path到你的项目下【如果用于测试,请如下 多用一个架包】 3.

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

下载地址如下:

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

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

 

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

 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 }
View Code

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

  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 }
View Code

 

5.完成  自行研究

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
相关文章
|
1月前
|
NoSQL Java MongoDB
java连接MongoDB
java连接MongoDB
|
4月前
|
NoSQL Java MongoDB
java接入MongoDB
java接入MongoDB
22 0
|
14天前
|
NoSQL Java 关系型数据库
Java基础教程(21)-Java连接MongoDB
【4月更文挑战第21天】MongoDB是开源的NoSQL数据库,强调高性能和灵活性。Java应用通过MongoDB Java驱动与之交互,涉及MongoClient、MongoDatabase、MongoCollection和Document等组件。连接MongoDB的步骤包括:配置连接字符串、创建MongoClient、选择数据库和集合。伪代码示例展示了如何建立连接、插入和查询数据。
|
15天前
|
运维 NoSQL Java
Serverless 应用引擎产品使用之在函数计算上部署Java服务并访问阿里云MongoDB如何解决
阿里云Serverless 应用引擎(SAE)提供了完整的微服务应用生命周期管理能力,包括应用部署、服务治理、开发运维、资源管理等功能,并通过扩展功能支持多环境管理、API Gateway、事件驱动等高级应用场景,帮助企业快速构建、部署、运维和扩展微服务架构,实现Serverless化的应用部署与运维模式。以下是对SAE产品使用合集的概述,包括应用管理、服务治理、开发运维、资源管理等方面。
16 0
|
3月前
|
NoSQL Java MongoDB
java 连接mongodb的样例代码
java 连接mongodb的样例代码
|
8月前
|
NoSQL JavaScript Java
MongoDB 入门教程系列之一:开发环境搭建以及 Node.js 和 Java 的读写访问
MongoDB 入门教程系列之一:开发环境搭建以及 Node.js 和 Java 的读写访问
83 0
|
10月前
|
NoSQL Java 数据库连接
四.MongoDB入门-Java操作MongoDB
MongoDB入门-Java操作MongoDB
|
NoSQL Java 数据库
|
NoSQL Java 数据库