添加依赖
您需要在您的 Java 项目中添加 MongoDB Java 驱动的依赖,如果您使用 Maven,请在 pom.xml 中添加以下内容:

<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.11.1</version> <!-- 请检查官网获取最新版本 -->
</dependency>
如果您使用 Gradle,则在 build.gradle 中添加:
implementation 'org.mongodb:mongodb-driver-sync:4.11.1' // 请检查官网获取最新版本
建立连接
所有操作的第一步都是创建一个 MongoClient 并连接到 MongoDB 服务器。
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
public class MongoConnectionExample {
public static void main(String[] args) {
// --- 方式一:连接到默认地址 (localhost:27017) ---
// MongoClient mongoClient = MongoClients.create();
// --- 方式二:指定连接字符串 ---
String uri = "mongodb://localhost:27017";
MongoClient mongoClient = MongoClients.create(uri);
try {
// 获取数据库 (如果数据库不存在,MongoDB 会在第一次插入数据时创建)
MongoDatabase database = mongoClient.getDatabase("myDatabase");
// 获取集合 (类似于关系型数据库中的表)
MongoCollection<Document> collection = database.getCollection("users");
System.out.println("成功连接到数据库和集合!");
// ... 在这里执行其他操作 ...
} finally {
// 操作完成后,关闭客户端连接
mongoClient.close();
}
}
}
核心操作 (CRUD)
这是最常用的部分,我们以一个名为 users 的集合为例,该集合的结构如下:
{
"_id": ObjectId("..."),
"name": "Alice",
"age": 30,
"city": "New York",
"hobbies": ["reading", "hiking"]
}
A. 创建 - Insert
- 插入单个文档
// 1. 创建一个 Document 对象,表示要插入的文档
Document doc = new Document("name", "Bob")
.append("age", 25)
.append("city", "London")
.append("hobbies", Arrays.asList("coding", "gaming"));
// 2. 插入到集合中
collection.insertOne(doc);
System.out.println("文档插入成功!");
- 插入多个文档
List<Document> docs = new ArrayList<>();
docs.add(new Document("name", "Charlie").append("age", 35).append("city", "Paris"));
docs.add(new Document("name", "David").append("age", 28).append("city", "Berlin"));
collection.insertMany(docs);
System.out.println("多个文档插入成功!");
B. 读取 - Find
- 查找所有文档
// 创建一个 FindIterable<Document> 对象,它包含了所有匹配的文档
FindIterable<Document> findIterable = collection.find();
// 遍历并打印结果
for (Document cur : findIterable) {
System.out.println(cur.toJson());
}
- 按条件查找 (使用 Filters)
Filters 是 MongoDB Java 驱动提供的查询构建器,非常强大。

import static com.mongodb.client.model.Filters.*;
// 1. 查找 age 为 30 的用户
Document query1 = collection.find(eq("age", 30)).first();
System.out.println("找到 age=30 的用户: " + query1.toJson());
// 2. 查找 city 为 "New York" 且 age > 25 的用户
// 使用 and 组合多个条件
FindIterable<Document> findIterable2 = collection.find(
and(
eq("city", "New York"),
gt("age", 25)
)
);
findIterable2.forEach(doc -> System.out.println("找到符合条件的用户: " + doc.toJson()));
// 3. 查找 name 包含 "li" (不区分大小写) 的用户
// 使用正则表达式
FindIterable<Document> findIterable3 = collection.find(
regex("name", "li", "i") // "i" 表示不区分大小写
);
findIterable3.forEach(doc -> System.out.println("找到 name 包含 li 的用户: " + doc.toJson()));
- 投影 (只返回需要的字段)
// 查找所有用户,但只返回 name 和 city 字段,_id 默认返回
FindIterable<Document> findIterable4 = collection.find()
.projection(include("name", "city")); // 或者 .exclude("age", "hobbies")
findIterable4.forEach(doc -> System.out.println("投影结果: " + doc.toJson()));
- 排序
// 按 age 降序排列
FindIterable<Document> findIterable5 = collection.find().sort(descending("age"));
findIterable5.forEach(doc -> System.out.println("按 age 降序排列: " + doc.toJson()));
// 按 age 升序排列
// FindIterable<Document> findIterable5 = collection.find().sort(ascending("age"));
- 分页 (Limit 和 Skip)
// 跳过前 2 个文档,然后只取 1 个文档
FindIterable<Document> findIterable6 = collection.find().skip(2).limit(1);
findIterable6.forEach(doc -> System.out.println("分页结果: " + doc.toJson()));
C. 更新 - Update
- 更新单个文档
// 将 name 为 "Alice" 的用户的 age 更新为 31
// 使用 Updates 来构建更新操作
UpdateResult updateResult = collection.updateOne(
eq("name", "Alice"),
new Document("$set", new Document("age", 31))
);
System.out.println("匹配的文档数: " + updateResult.getMatchedCount());
System.out.println("修改的文档数: " + updateResult.getModifiedCount());
- 更新多个文档
// 将所有 city 为 "London" 的用户的 city 更新为 "UK London"
UpdateResult updateResultMany = collection.updateMany(
eq("city", "London"),
new Document("$set", new Document("city", "UK London"))
);
System.out.println("匹配的文档数: " + updateResultMany.getMatchedCount());
System.out.println("修改的文档数: " + updateResultMany.getModifiedCount());
- 删除字段
// 从所有文档中删除 "hobbies" 字段
UpdateResult updateResultRemove = collection.updateMany(
new Document(), // 空的 Document 表示匹配所有文档
new Document("$unset", new Document("hobbies", ""))
);
System.out.println("删除 'hobbies' 字段的文档数: " + updateResultRemove.getModifiedCount());
D. 删除 - Delete
- 删除单个文档
// 删除 name 为 "Bob" 的第一个匹配的文档
DeleteResult deleteResult = collection.deleteOne(eq("name", "Bob"));
System.out.println("删除的文档数: " + deleteResult.getDeletedCount());
- 删除多个文档
// 删除所有 age 小于 30 的文档
DeleteResult deleteResultMany = collection.deleteMany(lt("age", 30));
System.out.println("删除的文档数: " + deleteResultMany.getDeletedCount());
- 删除所有文档
// 删除集合中的所有文档,但保留集合本身 collection.deleteMany(new Document());
高级操作
A. 聚合
聚合操作用于处理数据记录并返回计算结果,它使用管道的概念,每个管道阶段对数据进行转换。
// 假设我们想按 city 分组,并计算每个城市的用户总数
List<Document> pipeline = Arrays.asList(
// 第一阶段:按 city 字段分组
new Document("$group",
new Document("_id", "$city") // _id 字段存储分组键,这里是 "city" 字段的值
.append("totalUsers", new Document("$sum", 1)) // 为每个分组创建一个 totalUsers 字段,并计算数量
),
// 第二阶段:按 totalUsers 降序排序
new Document("$sort",
new Document("totalUsers", -1)
)
);
// 执行聚合查询
AggregateIterable<Document> output = collection.aggregate(pipeline);
// 打印结果
output.forEach(doc -> System.out.println("聚合结果: " + doc.toJson()));
B. 索引管理
索引可以大大提高查询性能。
- 创建升序索引
// 在 "name" 字段上创建一个升序索引
collection.createIndex(new Document("name", 1));
System.out.println("索引创建成功");
- 查看所有索引
ListIndexesIterable<Document> indexes = collection.listIndexes();
indexes.forEach(doc -> System.out.println("索引信息: " + doc.toJson()));
- 删除索引
// 通过索引名称删除
collection.dropIndex("name_1");
// 或者通过索引特征删除
collection.dropIndex(new Document("name", 1));
使用 POJO (Plain Old Java Object)
直接使用 Document 很灵活,但类型不安全,更推荐的方式是使用 Java 对象。
- 创建 POJO 类
import org.bson.types.ObjectId;
import java.util.List;
public class User {
private ObjectId id;
private String name;
private int age;
private String city;
private List<String> hobbies;
// Getters and Setters (必须要有)
public ObjectId getId() { return id; }
public void setId(ObjectId id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
public List<String> getHobbies() { return hobbies; }
public void setHobbies(List<String> hobbies) { this.hobbies = hobbies; }
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", city='" + city + '\'' +
", hobbies=" + hobbies +
'}';
}
}
- 在代码中使用
// 1. 创建 CodecRegistry 并注册你的 POJO 类
CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(
MongoClient.getDefaultCodecRegistry(),
CodecRegistgers.fromProviders(PojoCodecProvider.builder()
.register(User.class)
.build())
);
// 2. 在获取集合时应用这个 CodecRegistry
// 注意:这里需要使用 BsonDocument 来构建查询,或者使用 com.mongodb.client.model.Filters
// 对于查询,通常还是用 Filters,但对于结果映射,CodecRegistry 会自动处理
// 为了简单起见,我们直接使用 collection.find() 的重载方法
collection = database.getCollection("users", User.class);
// 插入 POJO 对象
User newUser = new User();
newUser.setName("Eve");
newUser.setAge(40);
newUser.setCity("Rome");
newUser.setHobbies(Arrays.asList("art", "travel"));
collection.insertOne(newUser);
// 查询并直接映射到 User 对象
User foundUser = collection.find(eq("name", "Eve")).first();
System.out.println("找到的 POJO 用户: " + foundUser);
| 操作类别 | 核心类/方法 | 描述 |
|---|---|---|
| 连接 | MongoClients.create() |
创建客户端连接 |
mongoClient.getDatabase("dbName") |
获取数据库 | |
database.getCollection("collName") |
获取集合 | |
| 创建 | collection.insertOne(doc) |
插入单个文档 |
collection.insertMany(list) |
插入多个文档 | |
| 读取 | collection.find() |
查找所有文档 |
collection.find(filter) |
按条件查找 | |
Filters.eq(), gt(), lt(), regex(), and(), or() |
构建查询条件 | |
.projection(include("field")) |
投影,选择返回字段 | |
.sort(descending("field")) |
排序 | |
.skip(N).limit(M) |
分页 | |
| 更新 | collection.updateOne(filter, update) |
更新单个文档 |
collection.updateMany(filter, update) |
更新多个文档 | |
Updates.set(), unset(), inc() |
构建更新操作 | |
| 删除 | collection.deleteOne(filter) |
删除单个文档 |
collection.deleteMany(filter) |
删除多个文档 | |
| 聚合 | collection.aggregate(pipeline) |
执行聚合管道 |
| 索引 | collection.createIndex(keys) |
创建索引 |
collection.listIndexes() |
列出索引 | |
collection.dropIndex(keys/name) |
删除索引 |
这份指南涵盖了 MongoDB Java 驱动最常用和核心的命令,建议结合官方文档进行更深入的学习:MongoDB Java Driver Documentation。

