Computer >> Máy Tính >  >> Lập trình >> Java

Cách tạo chỉ mục trong MongoDB bằng Java?


Trong MongoDB để tạo chỉ mục, bạn cần sử dụng createIndex () phương pháp.

Cú pháp

db.COLLECTION_NAME.createIndex({KEY:1})

Trong đó khóa là tên của tệp mà bạn muốn tạo chỉ mục và 1 là cho thứ tự tăng dần. Để tạo chỉ mục theo thứ tự giảm dần, bạn cần sử dụng -1.

Trong Java, bạn có thể tạo Chỉ mục bằng cách sử dụng createIndex () phương thức này, với phương thức này, bạn cần chuyển loại chỉ mục (tăng dần hoặc giảm dần) và tên trường mà bạn muốn tạo chỉ mục, dưới dạng -

createIndex(Indexes.descinding("name"));

Ví dụ

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());
      }
   }
}

Đầu ra

Index created successfully
{"v": 2, "key": {"_id": 1}, "name": "_id_", "ns": "myDatabase.sampleCollection"}
{"v": 2, "key": {"age": 1}, "name": "age_1", "ns": "myDatabase.sampleCollection"}