如何使用 Java 在 MongoDB 中创建索引?
javaobject oriented programmingprogramming更新于 2025/10/7 23:08:17
在 MongoDB 中创建索引,您需要使用 createIndex() 方法。
语法
db.COLLECTION_NAME.createIndex({KEY:1})
其中 key 是要在其上创建索引的文件的名称,1 表示升序。要按降序创建索引,您需要使用 -1。
在 Java 中,您可以使用 createIndex() 方法创建索引,对于此方法,您需要传递索引的类型(升序或降序)和要在其上创建索引的字段名称,作为 −
createIndex(Indexes.descinding("name"));
示例
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Indexes;
import org.bson.Document;
import com.mongodb.MongoClient;
public class CreatingIndex {
public static void main( String args[] ) {
//创建 MongoDB 客户端
MongoClient mongo = new MongoClient( "localhost" , 27017 );
//访问数据库
MongoDatabase database = mongo.getDatabase("myDatabase");
//创建集合
database.createCollection("sampleCollection");
//检索要在其上创建索引的集合
MongoCollection<Document> coll = database.getCollection("sampleCollection");
//创建索引
coll.createIndex(Indexes.ascending("age"));
System.out.println("Index created successful");
//打印集合中的索引列表
for (Document index : coll.listIndexes()) {
System.out.println(index.toJson());
}
}
}
输出
Index created successfully
{"v": 2, "key": {"_id": 1}, "name": "_id_", "ns": "myDatabase.sampleCollection"}
{"v": 2, "key": {"age": 1}, "name": "age_1", "ns": "myDatabase.sampleCollection"}
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

