在 MongoDB 中使用 Java 创建索引
在 MongoDB 中使用 Java 驱动程序创建索引是一个常见操作,以下是详细的步骤和代码示例:

基本步骤
- 获取 MongoDB 集合对象
- 调用
createIndex()方法创建索引 - 可选:设置索引选项(如唯一性、过期时间等)
代码示例
创建简单索引
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class CreateIndexExample {
public static void main(String[] args) {
// 连接到 MongoDB
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("testdb");
MongoCollection<Document> collection = database.getCollection("users");
// 创建单字段索引
collection.createIndex(new Document("username", 1));
System.out.println("单字段索引创建成功");
mongoClient.close();
}
}
创建复合索引
// 创建复合索引
collection.createIndex(new Document("username", 1).append("email", -1));
System.out.println("复合索引创建成功");
创建唯一索引
// 创建唯一索引
collection.createIndex(new Document("email", 1), new IndexOptions().unique(true));
System.out.println("唯一索引创建成功");
创建 TTL 索引(自动过期文档)
// 创建 TTL 索引,30分钟后过期
collection.createIndex(new Document("createdAt", 1),
new IndexOptions().expireAfter(30L, TimeUnit.MINUTES));
System.out.println("TTL 索引创建成功");
创建部分索引(MongoDB 3.2+)
// 创建部分索引,只索引 age > 18 的文档
collection.createIndex(
new Document("age", 1),
new IndexOptions().partialFilterExpression(new Document("age", new Document("$gt", 18))));
System.out.println("部分索引创建成功");
创建文本索引
// 创建文本索引
collection.createIndex(new Document("name", "text").append("description", "text"));
System.out.println("文本索引创建成功");
创建地理空间索引
// 创建 2D 索引
collection.createIndex(new Document("location", "2dsphere"));
System.out.println("地理空间索引创建成功");
高级选项
可以通过 IndexOptions 类设置更多索引选项:
IndexOptions options = new IndexOptions()
.name("myCustomIndexName") // 自定义索引名称
.unique(true) // 唯一索引
.sparse(true) // 稀疏索引
.background(true) // 后台创建索引
.expireAfter(3600, TimeUnit.SECONDS) // TTL 索引
.partialFilterExpression(new Document("status", "active")); // 部分索引条件
collection.createIndex(new Document("username", 1), options);
检查现有索引
// 获取集合的所有索引
ListIndexesIterable<Document> indexes = collection.listIndexes();
for (Document index : indexes) {
System.out.println(index.toJson());
}
删除索引
// 删除指定索引
collection.dropIndex("username_1");
// 删除所有索引(除了 _id 索引)
collection.dropIndexes();
注意事项
- 索引创建是阻塞操作,除非使用
background(true)选项 - 复合索引中字段的顺序很重要,会影响查询性能
- TTL 索引只能用于日期/时间字段
- 唯一索引会阻止插入重复值,但可以插入多个 null 值(除非使用
partialFilterExpression)
代码示例使用了 MongoDB Java 驱动程序的最新 API(4.x+ 版本),如果你使用的是旧版本,语法可能略有不同。

