除了通过启动 mongo 进程进如 Shell 环境访问数据库外,MongoDB 还提供了其他基于编程语言的访问数据库方法。MongoDB 官方提供了 Java 语言的驱动包,利用这些驱动包可使用多种编程方法来连接并操作 MongoDB 数据库。
想要在 Java 程序中使用 MongoDB,需要确保您的电脑上已经安装了 MongoDB,并搭建好了 Java 的环境。
本篇内容主要介绍:Java 实现对 MongDB 的操作、Java 操作 MongoDB 数据库 Demo
一、Java 实现对 MongDB 的操作
1、前提条件
除了通过启动 mongo 进程进如 Shell 环境访问数据库外,MongoDB 还提供了其他基于编程语言的访问数据库方法。MongoDB 官方提供了 Java 语言的驱动包,利用这些驱动包可使用多种编程方法来连接并操作 MongoDB 数据库。
想要在 Java 程序中使用 MongoDB,需要确保您的电脑上已经安装了 MongoDB,并搭建好了 Java 的环境。
2、添加依赖
在 Maven 中添加以下依赖来使用操作 MongoDB 数据库:
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>3.12.11</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.12.11</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-core</artifactId>
<version>3.12.11</version>
</dependency>
...
</dependencies>
二、Java 操作 MongoDB 数据库 Demo
1、连接数据库
package com.lizhengi.demo;
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
/**
* @author liziheng
* @version 1.0.0
* @description 连接数据库
* @date 2023-01-04 5:19 下午
**/
public class ConnectToMongodb {
public static void main(String[] args) {
// 创建 MongoDB 连接
MongoClient mongo = new MongoClient("localhost", 27017);
// 连接到 MongoDB
MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
System.out.println("Credentials ::" + credential);
// 访问数据库
MongoDatabase database = mongo.getDatabase("lizhengi");
System.out.println("Connect to database successfully!");
System.out.println("MongoDatabase info is : " + database.getName());
}
}
运行 Main 函数,返回以下结果:
Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi
2、创建集合
package com.lizhengi.demo;
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
/**
* @author liziheng
* @version 1.0.0
* @description 创建集合
* @date 2023-01-04 7:36 下午
**/
public class CreatingCollection {
public static void main(String[] args) {
// 创建 MongoDB 连接
MongoClient mongo = new MongoClient("localhost", 27017);
// 连接到 MongoDB
MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
System.out.println("Credentials ::" + credential);
// 访问数据库
MongoDatabase database = mongo.getDatabase("lizhengi");
System.out.println("Connect to database successfully!");
System.out.println("MongoDatabase info is : " + database.getName());
// 创建集合
database.createCollection("lizhengi_test_3");
System.out.println("create collection successfully!");
}
}
运行 Main 函数,返回以下结果:
Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengicreate collection successfully!
3、列出所有集合
package com.lizhengi.demo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
/**
* @author liziheng
* @version 1.0.0
* @description 列出所有集合
* @date 2023-01-04 7:56 下午
**/
public class ListOfCollection {
public static void main(String[] args) {
// 创建 MongoDB 连接
MongoClient mongo = new MongoClient("localhost", 27017);
// 连接到 MongoDB
MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
System.out.println("Credentials ::" + credential);
// 访问数据库
MongoDatabase database = mongo.getDatabase("lizhengi");
System.out.println("Connect to database successfully!");
System.out.println("MongoDatabase info is : " + database.getName());
// 检索集合列表
for (String name : database.listCollectionNames()) {
System.out.println(name);
}
}
}
运行 Main 函数,返回以下结果:
Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengilizhengi
lizhengi_test_3
lizhengi_test_2
4、获取/选择集合
package com.lizhengi.demo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
/**
* @author liziheng
* @version 1.0.0
* @description 获取/选择集合
* @date 2023-01-04 7:40 下午
**/
public class SelectingCollection {
public static void main(String[] args) {
// 创建 MongoDB 连接
MongoClient mongo = new MongoClient("localhost", 27017);
// 连接到 MongoDB
MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
System.out.println("Credentials ::" + credential);
// 访问数据库
MongoDatabase database = mongo.getDatabase("lizhengi");
System.out.println("Connect to database successfully!");
System.out.println("MongoDatabase info is : " + database.getName());
// 创建集合
MongoCollection<Document> collection = database.getCollection("lizhengi");
System.out.println("chose collection : " + collection.getNamespace());
}
}
运行 Main 函数,返回以下结果:
Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi
chose collection : lizhengi.lizhengi
5、插入文档
package com.lizhengi.demo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
/**
* @author liziheng
* @version 1.0.0
* @description 插入文档
* @date 2023-01-04 7:45 下午
**/
public class InsertingDocument {
public static void main(String[] args) {
// 创建 MongoDB 连接
MongoClient mongo = new MongoClient("localhost", 27017);
// 连接到 MongoDB
MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
System.out.println("Credentials ::" + credential);
// 访问数据库
MongoDatabase database = mongo.getDatabase("lizhengi");
System.out.println("Connect to database successfully!");
System.out.println("MongoDatabase info is : " + database.getName());
// 检索集合
MongoCollection<Document> collection = database.getCollection("lizhengi");
System.out.println("chose collection : " + collection.getNamespace());
Document document = new Document("title", "MongoDB")
.append("description", "database")
.append("likes", 200)
.append("url", "https://lizhengi.blog.csdn.net/")
.append("by", "lizhengi");
// 将文档插入到集合中
collection.insertOne(document);
System.out.println("Document insert successfully!");
}
}
运行 Main 函数,返回以下结果:
Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi
chose collection : lizhengi.lizhengiDocument insert successfully!
6、查询文档
package com.lizhengi.demo;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
/**
* @author liziheng
* @version 1.0.0
* @description 查询文档
* @date 2023-01-04 7:52 下午
**/
public class RetrievingAllDocuments {
public static void main(String[] args) {
// 创建 MongoDB 连接
MongoClient mongo = new MongoClient("localhost", 27017);
// 连接到 MongoDB
MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
System.out.println("Credentials ::" + credential);
// 访问数据库
MongoDatabase database = mongo.getDatabase("lizhengi");
System.out.println("Connect to database successfully!");
System.out.println("MongoDatabase info is : " + database.getName());
// 检索集合
MongoCollection<Document> collection = database.getCollection("lizhengi");
System.out.println("chose collection : " + collection.getNamespace());
// 获取 iterable 对象
FindIterable<Document> iterDoc = collection.find();
int i = 1;
// 获取迭代器
for (Document document : iterDoc) {
System.out.println(document);
i++;
}
}
}
运行 Main 函数,返回以下结果:
Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi
chose collection : lizhengi.lizhengiDocument{{_id=63b5676adcb7bc291eb5285d, title=MongoDB, description=database, likes=200, url=https://lizhengi.blog.csdn.net/, by=lizhengi}}
Document{{_id=63b568fa76a0f93c0a6c9f2a, title=MongoDB, description=database, likes=200, url=https://lizhengi.blog.csdn.net/, by=lizhengi2}}
7、更新文档
package com.lizhengi.demo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import org.bson.Document;
/**
* @author liziheng
* @version 1.0.0
* @description 更新文档
* @date 2023-01-04 7:59 下午
**/
public class UpdatingDocuments {
public static void main(String[] args) {
// 创建 MongoDB 连接
MongoClient mongo = new MongoClient("localhost", 27017);
// 连接到 MongoDB
MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
System.out.println("Credentials ::" + credential);
// 访问数据库
MongoDatabase database = mongo.getDatabase("lizhengi");
System.out.println("Connect to database successfully!");
System.out.println("MongoDatabase info is : " + database.getName());
// 检索集合
MongoCollection<Document> collection = database.getCollection("lizhengi");
System.out.println("chose collection : " + collection.getNamespace());
// 更新单个可用 updateOne
collection.updateMany(Filters.eq("title", "MongoDB"), Updates.set("likes", 150));
System.out.println("Document update successfully...");
// 更新后检索文档
// 获取 iterable 对象
FindIterable<Document> iterDoc = collection.find();
int i = 1;
// 获取迭代器
for (Document document : iterDoc) {
System.out.println(document);
i++;
}
}
}
运行 Main 函数,返回以下结果:
Credentials ::MongoCredential{mechanism=null, userName='lizhengi', source='lizhengi', password=<hidden>, mechanismProperties=<hidden>} Connect to database successfully! MongoDatabase info is : lizhengi chose collection : lizhengi.lizhengi Document update successfully... Document{{_id=63b5676adcb7bc291eb5285d, title=MongoDB, description=database, likes=150, url=https://lizhengi.blog.csdn.net/, by=lizhengi}} Document{{_id=63b568fa76a0f93c0a6c9f2a, title=MongoDB, description=database, likes=200, url=https://lizhengi.blog.csdn.net/, by=lizhengi2}}
8、删除文档
package com.lizhengi.demo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
/**
* @author liziheng
* @version 1.0.0
* @description 删除文档
* @date 2023-01-04 8:03 下午
**/
public class DeletingDocuments {
public static void main(String[] args) {
// 创建 MongoDB 连接
MongoClient mongo = new MongoClient("localhost", 27017);
// 连接到 MongoDB
MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
System.out.println("Credentials ::" + credential);
// 访问数据库
MongoDatabase database = mongo.getDatabase("lizhengi");
System.out.println("Connect to database successfully!");
System.out.println("MongoDatabase info is : " + database.getName());
// 检索集合
MongoCollection<Document> collection = database.getCollection("lizhengi");
System.out.println("chose collection : " + collection.getNamespace());
// 删除文档 删除多个可用 deleteMany
collection.deleteOne(Filters.eq("title", "MongoDB"));
System.out.println("Document delete successfully...");
// 删除后检索文档
// 获取 iterable 对象
FindIterable<Document> iterDoc = collection.find();
int i = 1;
// 获取迭代器
for (Document document : iterDoc) {
System.out.println(document);
i++;
}
}
}
运行 Main 函数,返回以下结果:
Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi
chose collection : lizhengi.lizhengiDocument delete successfully…
Document{{_id=63b568fa76a0f93c0a6c9f2a, title=MongoDB, description=database, likes=200, url=https://lizhengi.blog.csdn.net/, by=lizhengi2}}
9、删除集合
package com.lizhengi.demo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
/**
* @author liziheng
* @version 1.0.0
* @description 删除集合
* @date 2023-01-04 8:06 下午
**/
public class DropingCollection {
public static void main(String[] args) {
// 创建 MongoDB 连接
MongoClient mongo = new MongoClient("localhost", 27017);
// 连接到 MongoDB
MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
System.out.println("Credentials ::" + credential);
// 访问数据库
MongoDatabase database = mongo.getDatabase("lizhengi");
System.out.println("Connect to database successfully!");
System.out.println("MongoDatabase info is : " + database.getName());
// 检索集合
MongoCollection<Document> collection = database.getCollection("lizhengi_test_3");
System.out.println("chose collection : " + collection.getNamespace());
// 删除集合
collection.drop();
System.out.println("drop collection : " + collection.getNamespace());
// 检索集合列表
for (String name : database.listCollectionNames()) {
System.out.println(name);
}
}
}
运行 Main 函数,返回以下结果:
Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi
chose collection : lizhengi.lizhengi_test_3文章来源:https://www.toymoban.com/news/detail-603139.htmldrop collection : lizhengi.lizhengi_test_3
lizhengi
lizhengi_test_2文章来源地址https://www.toymoban.com/news/detail-603139.html
到了这里,关于MongoDB:在 Java 中使用 MongoDB的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!