如何使用 Java 在 MongoDB 中刪除索引?
要在 MongoDB 中刪除索引,需要使用 dropIndex() 方法。
語法
db.COLLECTION_NAME.dropIndex({KEY:1})在 Java 中,可以使用 dropIndex() 方法刪除索引,該方法需要傳入索引型別(升序或降序)和建立索引的欄位名。
dropIndex(Indexes.ascending("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 DroppingIndex {
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 coll = database.getCollection("sampleCollection");
//Creating indexes
coll.createIndex(Indexes.ascending("age"));
coll.createIndex(Indexes.ascending("name"));
System.out.println("List of colections: ");
for (Document index : coll.listIndexes()) {
System.out.println(index.toJson());
}
//Dropping the index
coll = database.getCollection("sampleCollection");
coll.dropIndex(Indexes.ascending("name"));
System.out.println("List of colections after deleting one ");
for (Document index : coll.listIndexes()) {
System.out.println(index.toJson());
}
}
}輸出
List of colections:
{"v": 2, "key": {"_id": 1}, "name": "_id_", "ns": "myDatabase.sampleCollection"}
{"v": 2, "key": {"age": 1}, "name": "age_1", "ns": "myDatabase.sampleCollection"}
{"v": 2, "key": {"name": 1}, "name": "name_1", "ns":
"myDatabase.sampleCollection"}
List of colections after deleting one
{"v": 2, "key": {"_id": 1}, "name": "_id_", "ns": "myDatabase.sampleCollection"}
{"v": 2, "key": {"age": 1}, "name": "age_1", "ns": "myDatabase.sampleCollection"}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP