如何使用 Java 在 MongoDB 中建立索引?
在 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[] ) { //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"}
廣告