创建高效MongoDB索引需遵循以下原则并配合实用策略:
db.collection.createIndex({ field: 1 })。db.collection.createIndex({ user_id: 1, create_time: -1 })。db.collection.createIndex({ name: 1, age: 1 })用于find({ name: "Alice" }, { _id: 0, name: 1, age: 1 })。partialFilterExpression仅索引满足条件的数据,减少索引体积,如db.products.createIndex({ price: 1 }, { partialFilterExpression: { price: { $gt: 0 } } })。db.collection.getIndexes()查看并清理。explain("executionStats")分析查询是否命中索引,优化执行计划。db.collection.reIndex()。near等操作。$text操作符。db.users.createIndex({ email: 1 }, { unique: true })。通过以上策略,可显著提升MongoDB查询效率,降低资源消耗。