Mongodb索引
mongodb也是有索引的,刚刚试了一下,没加索引,百万数据查询1.8秒。
加了索引同样的查询耗时15毫秒
索引的创建
使用shell进行索引创建
// 创建一个升序索引(默认)
db.collection.createIndex({ "fieldName": 1 })
// 创建一个降序索引
db.collection.createIndex({ "fieldName": -1 })
// 创建复合索引
db.collection.createIndex({ "field1": 1, "field2": -1 })
// 创建唯一索引,确保字段值唯一
db.collection.createIndex({ "fieldName": 1 }, { unique: true })
// 创建文本索引
db.collection.createIndex({ "textField": "text" })
使用java代码进行创建
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Indexes;
import com.mongodb.client.model.CreateIndexOptions;
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("databaseName");
MongoCollection<Document> collection = database.getCollection("collectionName");
// 创建升序索引
collection.createIndex(Indexes.ascending("fieldName"));
// 创建降序索引
collection.createIndex(Indexes.descending("fieldName"));
// 创建复合索引
collection.createIndex(Indexes.compoundIndex(Indexes.ascending("field1"), Indexes.descending("field2")));
// 创建唯一索引
collection.createIndex(Indexes.ascending("fieldName"), new CreateIndexOptions().unique(true));
// 文本索引在Java驱动中需要指定为文本搜索
collection.createIndex(new Document("textField", "text"));
索引的删除
在MongoDB中删除索引,可以使用以下命令:
在Mongo Shell中删除索引
-
删除指定的单字段索引:
db.collection.dropIndex({ "fieldName": 1 })
-
删除复合索引:
db.collection.dropIndex({ "field1": 1, "field2": -1 })
-
删除索引时不需要提供完整的索引定义,可以直接使用索引名称(可以通过
db.collection.getIndexes()
获取索引列表和名称):db.collection.dropIndex("indexName")
-
删除集合中的所有索引(不推荐在生产环境中随意使用此操作):
db.collection.dropIndexes()
使用Java驱动程序删除索引
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.IndexModel;
import com.mongodb.client.model.Indexes;
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("databaseName");
MongoCollection<Document> collection = database.getCollection("collectionName");
// 删除特定索引,需要提供完整的索引模型或者索引名称
collection.dropIndex(new IndexModel(Indexes.ascending("fieldName")));
// 或者通过索引名称删除
collection.dropIndex("indexName");
// 删除所有索引
collection.dropIndexes();
请注意,在删除索引前,请确保您了解该索引对数据库性能的影响,并且根据实际需求决定是否有必要删除。同时,删除索引后,与之相关的查询性能可能会降低,尤其是对于那些原本依赖于该索引执行快速查找或排序的操作。