如何使用 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"}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP