前言
在现代软件开发中,数据库操作是至关重要的一环。MongoDB 作为一款流行的 NoSQL 数据库,以其灵活的数据模型、高扩展性和出色的性能,被广泛应用于各类项目中。本文将详细介绍如何在 Java 项目中使用 MongoDB,从项目创建、依赖导入,到数据库、集合、文档的各种操作,以及聚合查询等高级应用,帮助读者快速掌握在 Java 环境下操作 MongoDB 的技能。
一、创建项目
在开始使用 Java 操作 MongoDB 之前,我们首先需要创建一个 Java 项目。这里我们以 IDEA 作为开发工具,通过 IDEA 的项目创建向导,能够便捷地搭建起一个基于 Maven 的 Java 项目框架,为后续引入 MongoDB 相关依赖及开发代码奠定基础。
打开IDEA,点击文件-->新建-->项目
。
如下图所示,选择Java-->输入项目名-->选择位置-->选择Maven-->选择JDK-->点击创建
。
二、导入依赖
为了在 Java 项目中能够顺利操作 MongoDB,我们需要导入 MongoDB 的 Java 驱动依赖。Maven 是 Java 项目中常用的依赖管理工具,通过在pom.xml文件中添加 MongoDB 驱动的依赖配置,Maven 会自动下载并管理相关的依赖包,确保项目能够正确引用 MongoDB 的 API。
在pom.xml
文件中添加如下依赖配置。
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.9.1</version>
</dependency>
</dependencies>
添加依赖后如下图所示,点击右上角的刷新
图标下载配置MongoDB依赖包。
三、数据库操作
数据库操作是使用 MongoDB 的基础,包括连接到 MongoDB 服务器、切换数据库、查看所有数据库以及删除当前数据库等操作。这些操作能够帮助我们管理和维护数据库环境,确保数据存储在正确的数据库中,并能根据需求对数据库进行清理或切换。
// 数据库操作
private static void databaseOperation() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 1. 切换数据库
MongoDatabase database = mongoClient.getDatabase("db_demo1");
String databaseName = database.getName();
System.out.println("切换到数据库: " + databaseName);
// 2. 查看所有数据库
MongoIterable<String> listDatabaseNames = mongoClient.listDatabaseNames();
System.out.println("数据库列表: ");
for (String dbName : listDatabaseNames) {
System.out.println(dbName);
}
// 3. 删除当前数据库
database.drop();
System.out.println("删除当前数据库: " + databaseName);
// 关闭连接
mongoClient.close();
}
四、集合操作
集合在 MongoDB 中类似于关系型数据库中的表,用于存储一组文档。集合操作涵盖了创建集合、获取集合、查看所有集合以及删除当前集合等功能。通过这些操作,我们可以灵活地组织和管理数据的存储结构,根据业务需求创建或删除相应的集合。
// 集合操作
private static void collectionOperation() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("db_demo1");
// 创建集合
database.createCollection("c_demo1");
System.out.println("创建集合: c_demo1");
// 获取集合
MongoCollection<Document> collection = database.getCollection("c_demo1");
String collectionName = collection.getNamespace().getCollectionName();
System.out.println("切换到集合: " + collectionName);
// 查看所有集合
MongoIterable<String> listCollectionNames = database.listCollectionNames();
System.out.println("集合列表: ");
for (String collectionName1 : listCollectionNames) {
System.out.println(collectionName1);
}
// 删除当前集合
collection.drop();
System.out.println("删除当前集合: " + collectionName);
// 关闭连接
mongoClient.close();
}
五、文档操作
文档是 MongoDB 中数据存储的基本单元,类似于关系型数据库中的行记录。文档操作是 MongoDB 使用中最为频繁的部分,包括插入文档(单个、多个以及嵌套文档)、更新文档(单个和多个)、删除文档(单个和多个)以及查询文档(多种条件查询、投影查询、排序查询、分页查询等)。通过这些操作,我们可以对数据库中的数据进行全方位的管理和检索。
1. 插入文档
插入文档操作是向 MongoDB 集合中添加数据的方式。可以插入单个文档,也可以一次性插入多个文档,并且支持插入嵌套结构的文档。这使得我们能够根据实际业务数据的复杂程度,灵活地将数据存储到数据库中。
// 文档插入操作
private static void insertDocument() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 切换数据库
MongoDatabase database = mongoClient.getDatabase("db_demo2");
// 获取集合
MongoCollection<Document> collection = database.getCollection("c_demo2");
// 插入单个文档
Document document = new Document("name", "John")
.append("age", 30)
.append("city", "New York");
collection.insertOne(document);
System.out.println("单个文档插入成功");
// 插入多个文档
Document document1 = new Document("name", "Alice").append("age", 25).append("city", "Los Angeles");
Document document2 = new Document("name", "Bob").append("age", 35).append("city", "Chicago");
List<Document> documents = new ArrayList<>();
documents.add(document1);
documents.add(document2);
collection.insertMany(documents);
System.out.println("多个文档插入成功");
// 嵌套文档插入
ArrayList<Document> docList = new ArrayList<>();
ArrayList<Integer> scores = new ArrayList<>();
scores.add(80);
scores.add(90);
scores.add(75);
Document doc1 = new Document("name", "zhangsan").append("info", new Document("age", 30).append("address", "yunnan").append("hight", 176));
Document doc2 = new Document("name", "lisi").append("info", new Document("age", 31).append("address", "guizhou").append("hight", 175));
Document doc3 = new Document("name", "wangwu").append("scores", scores);
docList.add(doc1);
docList.add(doc2);
docList.add(doc3);
InsertManyResult insertManyResult = collection.insertMany(docList);
System.out.println("嵌套文档插入成功:" + insertManyResult.wasAcknowledged());
// 关闭连接
mongoClient.close();
}
2. 更新文档
更新文档操作允许我们根据指定的条件对已存在的文档进行修改。可以更新单个文档,也能批量更新多个文档。通过使用$set
等操作符,能够精确地指定需要更新的字段和值,确保数据的准确性和时效性。
// 更新文档
private static void updateDocument() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 切换数据库
MongoDatabase database = mongoClient.getDatabase("db_demo2");
// 获取集合
MongoCollection<Document> collection = database.getCollection("c_demo2");
// 1. 更新单个文档
Document filter = new Document("name", "Alice");
Document update = new Document("$set", new Document("age", 26));
UpdateResult updateResult = collection.updateOne(filter, update);
System.out.println("单个文档更新成功:" + updateResult.wasAcknowledged());
// 2. 更新多个文档
Document filter1 = new Document("age", new Document("$gt", 20));
Document update1 = new Document("$set", new Document("name", "new_name"));
UpdateResult updateResult1 = collection.updateMany(filter1, update1);
System.out.println("多个文档更新成功:" + updateResult1.wasAcknowledged());
// 关闭连接
mongoClient.close();
}
3. 删除文档
删除文档操作可以从 MongoDB 集合中移除不需要的数据。同样支持删除单个文档和多个文档,通过指定删除条件,能够精准地清理掉不再使用的数据,优化数据库存储空间。
// 删除文档
private static void deleteDocument() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 切换数据库
MongoDatabase database = mongoClient.getDatabase("db_demo2");
// 获取集合
MongoCollection<Document> collection = database.getCollection("c_demo2");
// 删除单个文档
Document filter = new Document("name", "new_name");
DeleteResult deleteResult = collection.deleteOne(filter);
System.out.println("删除单个文档成功:" + deleteResult.wasAcknowledged());
// 删除多个文档
Document filter1 = new Document("age", new Document("$gt", 30));
DeleteResult deleteResult1 = collection.deleteMany(filter1);
System.out.println("删除多个文档成功:" + deleteResult1.wasAcknowledged());
// 关闭连接
mongoClient.close();
}
4. 查询文档
查询文档是从 MongoDB 集合中获取数据的核心操作。通过构建不同的查询条件,如基于字段值的精确匹配、范围查询、数组元素查询等,以及使用投影来指定返回的字段,结合排序、分页等功能,能够满足各种复杂的数据检索需求。
// 查询文档
private static void queryDocuments() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 切换数据库
MongoDatabase database = mongoClient.getDatabase("db_demo2");
// 获取集合
MongoCollection<Document> collection = database.getCollection("c_demo2");
// 查询集合c_demo2中age等于 30 的所有文档
Document filter = new Document("age", 30);
FindIterable<Document> findIterable = collection.find(filter);
System.out.println("查询集合c_demo2中age等于 30 的所有文档:");
for (Document doc : findIterable) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中的所有文档
System.out.println("查询所有文档:");
for (Document doc : collection.find()) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中age大于等于 25 的所有文档
Document filter1 = new Document("age", new Document("$gte", 25));
FindIterable<Document> findIterable1 = collection.find(filter1);
System.out.println("查询集合c_demo2中age大于等于 25 的所有文档:");
for (Document doc : findIterable1) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中age大于 22 且小于 30 的所有文档
Document filter2 = new Document("age", new Document("$gt", 22).append("$lt", 30));
FindIterable<Document> findIterable2 = collection.find(filter2);
System.out.println("查询集合c_demo2中age大于 22 且小于 30 的所有文档:");
for (Document doc : findIterable2) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中 scores 数组中至少有一个元素大于 85 的文档。
Document filter3 = new Document("scores", new Document("$elemMatch", new Document("$gt", 85)));
FindIterable<Document> findIterable3 = collection.find(filter3);
System.out.println("查询集合c_demo2中 scores 数组中至少有一个元素大于 85 的文档:");
for (Document doc : findIterable3) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中 scores 数组长度为 3 的文档。
Document filter4 = new Document("scores", new Document("$size", 3));
FindIterable<Document> findIterable4 = collection.find(filter4);
System.out.println("查询集合c_demo2中 scores 数组长度为 3 的文档:");
for (Document doc : findIterable4) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中 name 和 city 字段,排除 _id 字段。
Document filter5 = new Document("name", 1).append("city", 1).append("_id", 0);
FindIterable<Document> findIterable5 = collection.find().projection(filter5);
System.out.println("查询集合c_demo2中 name 和 city 字段,排除 _id 字段:");
for (Document doc : findIterable5) {
System.out.println(doc.toJson());
}
// 排除 _id 和 name 字段。
Document filter6 = new Document("_id", 0).append("name", 0);
FindIterable<Document> findIterable6 = collection.find().projection(filter6);
System.out.println("排除 _id 和 name 字段:");
for (Document doc : findIterable6) {
System.out.println(doc.toJson());
}
// 返回第一个匹配的文档,而不是所有匹配的文档。
Document filter7 = new Document("name", "new_name");
Document doc7 = collection.find(filter7).first();
System.out.println("返回第一个匹配的文档:");
if (doc7 != null) {
System.out.println(doc7.toJson());
}
// 查询集合c_demo2的前两个文档。
FindIterable<Document> findIterable7 = collection.find().limit(2);
System.out.println("查询集合c_demo2的前两个文档:");
for (Document doc : findIterable7) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中跳过前3个文档的所有文档。
FindIterable<Document> findIterable8 = collection.find().skip(3);
System.out.println("查询集合c_demo2中跳过前3个文档的所有文档:");
for (Document doc : findIterable8) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中的所有文档,并按age进行升序排序。
FindIterable<Document> findIterable9 = collection.find().sort(new Document("age", 1));
System.out.println("查询集合c_demo2中的所有文档,并按age进行升序排序:");
for (Document doc : findIterable9) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中name为zhangsan,且嵌套文档info中age为 30 和address为yunnan的第一个匹配的文档。
Document filter10 = new Document("name", "zhangsan").append("info.age", 30).append("info.address", "yunnan");
Document doc10 = collection.find(filter10).first();
System.out.println("查询集合c_demo2中name为zhangsan,且嵌套文档info中age为 30 和address为yunnan的第一个匹配的文档:");
if (doc10 != null) {
System.out.println(doc10.toJson());
}
// 查询集合c_demo2中city的值以Los开头的所有文档。
Document filter11 = new Document("city", new Document("$regex", "^Los"));
FindIterable<Document> findIterable11 = collection.find(filter11);
System.out.println("查询集合c_demo2中city的值以Los开头的所有文档:");
for (Document doc : findIterable11) {
System.out.println(doc.toJson());
}
// 关闭连接
mongoClient.close();
}
5. 聚合查询
聚合查询是 MongoDB 中一种强大的数据处理方式,它允许我们对文档进行复杂的数据分析和处理。通过使用各种聚合操作符,如$group
、$match
、$sort
、$project
等,以对数据进行分组、过滤、排序、投影等操作,还能进行统计计算,如求和、求平均值、找出最小值和最大值等。这使得我们能够从大量数据中提取有价值的信息,满足复杂的业务分析需求。
// 聚合查询
private static void aggregateDocuments() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 切换数据库
MongoDatabase database = mongoClient.getDatabase("db_demo2");
// 获取集合
MongoCollection<Document> collection = database.getCollection("c_demo4");
// 插入多个文档
ArrayList<Document> arrayList = new ArrayList<>();
arrayList.add(new Document().append("category", "A").append("value", 10));
arrayList.add(new Document().append("category", "B").append("value", 20));
arrayList.add(new Document().append("category", "A").append("value", 30));
arrayList.add(new Document().append("category", "B").append("value", 40));
arrayList.add(new Document().append("category", "C").append("value", 50));
arrayList.add(new Document().append("category", "A").append("value", 10));
arrayList.add(new Document().append("category", "B").append("value", 20));
arrayList.add(new Document().append("category", "A").append("value", 30));
arrayList.add(new Document().append("category", "B").append("value", 40));
arrayList.add(new Document().append("category", "C").append("value", 50));
InsertManyResult insertManyResult = collection.insertMany(arrayList);
System.out.println("插入文档数量: " + insertManyResult.getInsertedIds().size());
System.out.println("插入文档结果:" + insertManyResult.wasAcknowledged());
// 使用 $group 计算每个类别的总和
List<Document> pipeline = new ArrayList<>();
pipeline.add(new Document("$group", new Document("_id", "$category").append("total", new Document("$sum", "$value"))));
AggregateIterable<Document> aggregateIterable = collection.aggregate(pipeline);
System.out.println("计算每个类别值的总和:");
for (Document doc : aggregateIterable) {
System.out.println(doc.toJson());
}
// 使用 $match 过滤出类别为A的文档。
List<Document> pipeline1 = new ArrayList<>();
pipeline1.add(new Document("$match", new Document("category", "A")));
AggregateIterable<Document> aggregateIterable1 = collection.aggregate(pipeline1);
System.out.println("过滤出类别为A的文档:");
for (Document doc : aggregateIterable1) {
System.out.println(doc.toJson());
}
// 使用 $sort 根据value的值对文档降序排序。
List<Document> pipeline2 = new ArrayList<>();
pipeline2.add(new Document("$sort", new Document("value", -1)));
AggregateIterable<Document> aggregateIterable2 = collection.aggregate(pipeline2);
System.out.println("根据value的值对文档降序排序:");
for (Document doc : aggregateIterable2) {
System.out.println(doc.toJson());
}
// 使用 $project 修改文档结构,不显示_id。
List<Document> pipeline3 = new ArrayList<>();
pipeline3.add(new Document("$project", new Document("_id", 0)));
AggregateIterable<Document> aggregateIterable3 = collection.aggregate(pipeline3);
System.out.println("使用 $project 修改文档结构,不显示_id:");
for (Document doc : aggregateIterable3) {
System.out.println(doc.toJson());
}
// 使用 $skip 和 $limit 分页查询。
List<Document> pipeline4 = new ArrayList<>();
pipeline4.add(new Document("$skip", 2));
pipeline4.add(new Document("$limit", 2));
AggregateIterable<Document> aggregateIterable4 = collection.aggregate(pipeline4);
System.out.println("使用 $skip 和 $limit 分页查询:");
for (Document doc : aggregateIterable4) {
System.out.println(doc.toJson());
}
// 使用 $avg 计算平均值,_id 为 null 表示不分组,即把整个集合视为一个单一的组。
List<Document> pipeline5 = new ArrayList<>();
pipeline5.add(new Document("$group", new Document("_id", null).append("average", new Document("$avg", "$value"))));
AggregateIterable<Document> aggregateIterable5 = collection.aggregate(pipeline5);
System.out.println("使用 $avg 计算平均值:");
for (Document doc : aggregateIterable5) {
System.out.println(doc.toJson());
}
// 使用 $min 和 $max 找出最小值和最大值。
List<Document> pipeline6 = new ArrayList<>();
pipeline6.add(new Document("$group", new Document("_id", null).append("min", new Document("$min", "$value")).append("max", new Document("$max", "$value"))));
AggregateIterable<Document> aggregateIterable6 = collection.aggregate(pipeline6);
System.out.println("使用 $min 和 $max 找出最小值和最大值:");
for (Document doc : aggregateIterable6) {
System.out.println(doc.toJson());
}
// 使用 $push 收集数组中的元素。
List<Document> pipeline7 = new ArrayList<>();
pipeline7.add(new Document("$group", new Document("_id", "$category").append("values", new Document("$push", "$value"))));
AggregateIterable<Document> aggregateIterable7 = collection.aggregate(pipeline7);
System.out.println("使用 $push 收集数组中的元素:");
for (Document doc : aggregateIterable7) {
System.out.println(doc.toJson());
}
// 使用 $first 和 $last 返回数组中的第一个和最后一个元素。
List<Document> pipeline8 = new ArrayList<>();
pipeline8.add(new Document("$group", new Document("_id", "$category").append("first", new Document("$first", "$value")).append("last", new Document("$last", "$value"))));
AggregateIterable<Document> aggregateIterable8 = collection.aggregate(pipeline8);
System.out.println("使用 $first 和 $last 返回数组中的第一个和最后一个元素:");
for (Document doc : aggregateIterable8) {
System.out.println(doc.toJson());
}
// 关闭连接
mongoClient.close();
}
六、完整代码
package org.example;
import com.mongodb.client.*;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.InsertManyResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// 数据库操作
// databaseOperation();
// 集合操作
// collectionOperation();
// 文档插入操作
// insertDocument();
// 更新文档
// updateDocument();
// 删除文档
// deleteDocument();
// 查询所有文档
// queryDocuments();
// 条件查询
// queryDocumentsByCondition(collection);
// 聚合查询
// aggregateDocuments();
}
// 数据库操作
private static void databaseOperation() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 1. 切换数据库
MongoDatabase database = mongoClient.getDatabase("db_demo1");
String databaseName = database.getName();
System.out.println("切换到数据库: " + databaseName);
// 2. 查看所有数据库
MongoIterable<String> listDatabaseNames = mongoClient.listDatabaseNames();
System.out.println("数据库列表: ");
for (String dbName : listDatabaseNames) {
System.out.println(dbName);
}
// 3. 删除当前数据库
database.drop();
System.out.println("删除当前数据库: " + databaseName);
// 关闭连接
mongoClient.close();
}
// 集合操作
private static void collectionOperation() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("db_demo1");
// 创建集合
database.createCollection("c_demo1");
System.out.println("创建集合: c_demo1");
// 获取集合
MongoCollection<Document> collection = database.getCollection("c_demo1");
String collectionName = collection.getNamespace().getCollectionName();
System.out.println("切换到集合: " + collectionName);
// 查看所有集合
MongoIterable<String> listCollectionNames = database.listCollectionNames();
System.out.println("集合列表: ");
for (String collectionName1 : listCollectionNames) {
System.out.println(collectionName1);
}
// 删除当前集合
collection.drop();
System.out.println("删除当前集合: " + collectionName);
// 关闭连接
mongoClient.close();
}
// 文档插入操作
private static void insertDocument() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 切换数据库
MongoDatabase database = mongoClient.getDatabase("db_demo2");
// 获取集合
MongoCollection<Document> collection = database.getCollection("c_demo2");
// 插入单个文档
Document document = new Document("name", "John")
.append("age", 30)
.append("city", "New York");
collection.insertOne(document);
System.out.println("单个文档插入成功");
// 插入多个文档
Document document1 = new Document("name", "Alice").append("age", 25).append("city", "Los Angeles");
Document document2 = new Document("name", "Bob").append("age", 35).append("city", "Chicago");
List<Document> documents = new ArrayList<>();
documents.add(document1);
documents.add(document2);
collection.insertMany(documents);
System.out.println("多个文档插入成功");
// 嵌套文档插入
ArrayList<Document> docList = new ArrayList<>();
ArrayList<Integer> scores = new ArrayList<>();
scores.add(80);
scores.add(90);
scores.add(75);
Document doc1 = new Document("name", "zhangsan").append("info", new Document("age", 30).append("address", "yunnan").append("hight", 176));
Document doc2 = new Document("name", "lisi").append("info", new Document("age", 31).append("address", "guizhou").append("hight", 175));
Document doc3 = new Document("name", "wangwu").append("scores", scores);
docList.add(doc1);
docList.add(doc2);
docList.add(doc3);
InsertManyResult insertManyResult = collection.insertMany(docList);
System.out.println("嵌套文档插入成功:" + insertManyResult.wasAcknowledged());
// 关闭连接
mongoClient.close();
}
// 更新文档
private static void updateDocument() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 切换数据库
MongoDatabase database = mongoClient.getDatabase("db_demo2");
// 获取集合
MongoCollection<Document> collection = database.getCollection("c_demo2");
// 1. 更新单个文档
Document filter = new Document("name", "Alice");
Document update = new Document("$set", new Document("age", 26));
UpdateResult updateResult = collection.updateOne(filter, update);
System.out.println("单个文档更新成功:" + updateResult.wasAcknowledged());
// 2. 更新多个文档
Document filter1 = new Document("age", new Document("$gt", 20));
Document update1 = new Document("$set", new Document("name", "new_name"));
UpdateResult updateResult1 = collection.updateMany(filter1, update1);
System.out.println("多个文档更新成功:" + updateResult1.wasAcknowledged());
// 关闭连接
mongoClient.close();
}
// 删除文档
private static void deleteDocument() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 切换数据库
MongoDatabase database = mongoClient.getDatabase("db_demo2");
// 获取集合
MongoCollection<Document> collection = database.getCollection("c_demo2");
// 删除单个文档
Document filter = new Document("name", "new_name");
DeleteResult deleteResult = collection.deleteOne(filter);
System.out.println("删除单个文档成功:" + deleteResult.wasAcknowledged());
// 删除多个文档
Document filter1 = new Document("age", new Document("$gt", 30));
DeleteResult deleteResult1 = collection.deleteMany(filter1);
System.out.println("删除多个文档成功:" + deleteResult1.wasAcknowledged());
// 关闭连接
mongoClient.close();
}
// 查询文档
private static void queryDocuments() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 切换数据库
MongoDatabase database = mongoClient.getDatabase("db_demo2");
// 获取集合
MongoCollection<Document> collection = database.getCollection("c_demo2");
// 查询集合c_demo2中age等于 30 的所有文档
Document filter = new Document("age", 30);
FindIterable<Document> findIterable = collection.find(filter);
System.out.println("查询集合c_demo2中age等于 30 的所有文档:");
for (Document doc : findIterable) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中的所有文档
System.out.println("查询所有文档:");
for (Document doc : collection.find()) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中age大于等于 25 的所有文档
Document filter1 = new Document("age", new Document("$gte", 25));
FindIterable<Document> findIterable1 = collection.find(filter1);
System.out.println("查询集合c_demo2中age大于等于 25 的所有文档:");
for (Document doc : findIterable1) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中age大于 22 且小于 30 的所有文档
Document filter2 = new Document("age", new Document("$gt", 22).append("$lt", 30));
FindIterable<Document> findIterable2 = collection.find(filter2);
System.out.println("查询集合c_demo2中age大于 22 且小于 30 的所有文档:");
for (Document doc : findIterable2) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中 scores 数组中至少有一个元素大于 85 的文档。
Document filter3 = new Document("scores", new Document("$elemMatch", new Document("$gt", 85)));
FindIterable<Document> findIterable3 = collection.find(filter3);
System.out.println("查询集合c_demo2中 scores 数组中至少有一个元素大于 85 的文档:");
for (Document doc : findIterable3) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中 scores 数组长度为 3 的文档。
Document filter4 = new Document("scores", new Document("$size", 3));
FindIterable<Document> findIterable4 = collection.find(filter4);
System.out.println("查询集合c_demo2中 scores 数组长度为 3 的文档:");
for (Document doc : findIterable4) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中 name 和 city 字段,排除 _id 字段。
Document filter5 = new Document("name", 1).append("city", 1).append("_id", 0);
FindIterable<Document> findIterable5 = collection.find().projection(filter5);
System.out.println("查询集合c_demo2中 name 和 city 字段,排除 _id 字段:");
for (Document doc : findIterable5) {
System.out.println(doc.toJson());
}
// 排除 _id 和 name 字段。
Document filter6 = new Document("_id", 0).append("name", 0);
FindIterable<Document> findIterable6 = collection.find().projection(filter6);
System.out.println("排除 _id 和 name 字段:");
for (Document doc : findIterable6) {
System.out.println(doc.toJson());
}
// 返回第一个匹配的文档,而不是所有匹配的文档。
Document filter7 = new Document("name", "new_name");
Document doc7 = collection.find(filter7).first();
System.out.println("返回第一个匹配的文档:");
if (doc7 != null) {
System.out.println(doc7.toJson());
}
// 查询集合c_demo2的前两个文档。
FindIterable<Document> findIterable7 = collection.find().limit(2);
System.out.println("查询集合c_demo2的前两个文档:");
for (Document doc : findIterable7) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中跳过前3个文档的所有文档。
FindIterable<Document> findIterable8 = collection.find().skip(3);
System.out.println("查询集合c_demo2中跳过前3个文档的所有文档:");
for (Document doc : findIterable8) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中的所有文档,并按age进行升序排序。
FindIterable<Document> findIterable9 = collection.find().sort(new Document("age", 1));
System.out.println("查询集合c_demo2中的所有文档,并按age进行升序排序:");
for (Document doc : findIterable9) {
System.out.println(doc.toJson());
}
// 查询集合c_demo2中name为zhangsan,且嵌套文档info中age为 30 和address为yunnan的第一个匹配的文档。
Document filter10 = new Document("name", "zhangsan").append("info.age", 30).append("info.address", "yunnan");
Document doc10 = collection.find(filter10).first();
System.out.println("查询集合c_demo2中name为zhangsan,且嵌套文档info中age为 30 和address为yunnan的第一个匹配的文档:");
if (doc10 != null) {
System.out.println(doc10.toJson());
}
// 查询集合c_demo2中city的值以Los开头的所有文档。
Document filter11 = new Document("city", new Document("$regex", "^Los"));
FindIterable<Document> findIterable11 = collection.find(filter11);
System.out.println("查询集合c_demo2中city的值以Los开头的所有文档:");
for (Document doc : findIterable11) {
System.out.println(doc.toJson());
}
// 关闭连接
mongoClient.close();
}
// 聚合查询
private static void aggregateDocuments() {
// 连接到 MongoDB 服务器
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 切换数据库
MongoDatabase database = mongoClient.getDatabase("db_demo2");
// 获取集合
MongoCollection<Document> collection = database.getCollection("c_demo4");
// 插入多个文档
ArrayList<Document> arrayList = new ArrayList<>();
arrayList.add(new Document().append("category", "A").append("value", 10));
arrayList.add(new Document().append("category", "B").append("value", 20));
arrayList.add(new Document().append("category", "A").append("value", 30));
arrayList.add(new Document().append("category", "B").append("value", 40));
arrayList.add(new Document().append("category", "C").append("value", 50));
arrayList.add(new Document().append("category", "A").append("value", 10));
arrayList.add(new Document().append("category", "B").append("value", 20));
arrayList.add(new Document().append("category", "A").append("value", 30));
arrayList.add(new Document().append("category", "B").append("value", 40));
arrayList.add(new Document().append("category", "C").append("value", 50));
InsertManyResult insertManyResult = collection.insertMany(arrayList);
System.out.println("插入文档数量: " + insertManyResult.getInsertedIds().size());
System.out.println("插入文档结果:" + insertManyResult.wasAcknowledged());
// 使用 $group 计算每个类别的总和
List<Document> pipeline = new ArrayList<>();
pipeline.add(new Document("$group", new Document("_id", "$category").append("total", new Document("$sum", "$value"))));
AggregateIterable<Document> aggregateIterable = collection.aggregate(pipeline);
System.out.println("计算每个类别值的总和:");
for (Document doc : aggregateIterable) {
System.out.println(doc.toJson());
}
// 使用 $match 过滤出类别为A的文档。
List<Document> pipeline1 = new ArrayList<>();
pipeline1.add(new Document("$match", new Document("category", "A")));
AggregateIterable<Document> aggregateIterable1 = collection.aggregate(pipeline1);
System.out.println("过滤出类别为A的文档:");
for (Document doc : aggregateIterable1) {
System.out.println(doc.toJson());
}
// 使用 $sort 根据value的值对文档降序排序。
List<Document> pipeline2 = new ArrayList<>();
pipeline2.add(new Document("$sort", new Document("value", -1)));
AggregateIterable<Document> aggregateIterable2 = collection.aggregate(pipeline2);
System.out.println("根据value的值对文档降序排序:");
for (Document doc : aggregateIterable2) {
System.out.println(doc.toJson());
}
// 使用 $project 修改文档结构,不显示_id。
List<Document> pipeline3 = new ArrayList<>();
pipeline3.add(new Document("$project", new Document("_id", 0)));
AggregateIterable<Document> aggregateIterable3 = collection.aggregate(pipeline3);
System.out.println("使用 $project 修改文档结构,不显示_id:");
for (Document doc : aggregateIterable3) {
System.out.println(doc.toJson());
}
// 使用 $skip 和 $limit 分页查询。
List<Document> pipeline4 = new ArrayList<>();
pipeline4.add(new Document("$skip", 2));
pipeline4.add(new Document("$limit", 2));
AggregateIterable<Document> aggregateIterable4 = collection.aggregate(pipeline4);
System.out.println("使用 $skip 和 $limit 分页查询:");
for (Document doc : aggregateIterable4) {
System.out.println(doc.toJson());
}
// 使用 $avg 计算平均值,_id 为 null 表示不分组,即把整个集合视为一个单一的组。
List<Document> pipeline5 = new ArrayList<>();
pipeline5.add(new Document("$group", new Document("_id", null).append("average", new Document("$avg", "$value"))));
AggregateIterable<Document> aggregateIterable5 = collection.aggregate(pipeline5);
System.out.println("使用 $avg 计算平均值:");
for (Document doc : aggregateIterable5) {
System.out.println(doc.toJson());
}
// 使用 $min 和 $max 找出最小值和最大值。
List<Document> pipeline6 = new ArrayList<>();
pipeline6.add(new Document("$group", new Document("_id", null).append("min", new Document("$min", "$value")).append("max", new Document("$max", "$value"))));
AggregateIterable<Document> aggregateIterable6 = collection.aggregate(pipeline6);
System.out.println("使用 $min 和 $max 找出最小值和最大值:");
for (Document doc : aggregateIterable6) {
System.out.println(doc.toJson());
}
// 使用 $push 收集数组中的元素。
List<Document> pipeline7 = new ArrayList<>();
pipeline7.add(new Document("$group", new Document("_id", "$category").append("values", new Document("$push", "$value"))));
AggregateIterable<Document> aggregateIterable7 = collection.aggregate(pipeline7);
System.out.println("使用 $push 收集数组中的元素:");
for (Document doc : aggregateIterable7) {
System.out.println(doc.toJson());
}
// 使用 $first 和 $last 返回数组中的第一个和最后一个元素。
List<Document> pipeline8 = new ArrayList<>();
pipeline8.add(new Document("$group", new Document("_id", "$category").append("first", new Document("$first", "$value")).append("last", new Document("$last", "$value"))));
AggregateIterable<Document> aggregateIterable8 = collection.aggregate(pipeline8);
System.out.println("使用 $first 和 $last 返回数组中的第一个和最后一个元素:");
for (Document doc : aggregateIterable8) {
System.out.println(doc.toJson());
}
// 关闭连接
mongoClient.close();
}
}