একটি সূচক তৈরি করতে 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"}