Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java를 사용하여 MongoDB에서 인덱스를 만드는 방법은 무엇입니까?


MongoDB에서 색인을 생성하려면 createIndex()를 사용해야 합니다. 방법.

구문

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

여기서 키는 인덱스를 생성하려는 파일의 이름이고 1은 오름차순입니다. 내림차순으로 색인을 생성하려면 -1을 사용해야 합니다.

자바에서는 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"}