如何使用Java在MongoDB中创建索引?
在MongoDB中创建索引,您需要使用createIndex()方法。
语法
db.COLLECTION_NAME.createIndex({KEY:1})
其中的键是要在其上创建索引的文件的名称,而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[] ) { //Creating a MongoDB client MongoClient mongo = new MongoClient( "localhost" , 27017 ); //Accessing the database MongoDatabase database = mongo.getDatabase("myDatabase"); //Creating a collection database.createCollection("sampleCollection"); //Retrieving the collection on which you want to create the index MongoCollection<Document> coll = database.getCollection("sampleCollection"); //Creating an index coll.createIndex(Indexes.ascending("age")); System.out.println("Index created successfully"); //Printing the list of indices in the collection 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"}