当架构发生变化时,无需删除集合并重新创建它。
更多信息:
稀疏索引仅包含具有索引字段的文档的条目,即使索引字段包含空值。索引会跳过任何缺少索引字段的文档。索引是“稀疏的”,因为它不包括集合的所有文档。相比之下,非稀疏索引包含集合中的所有文档,为那些不包含索引字段的文档存储空值。
稀疏索引和不完整结果
如果稀疏索引会导致查询和排序操作的结果集不完整,MongoDB 将不会使用该索引,除非hint() 明确指定索引。
拥有稀疏索引并不会阻止我们插入带有或不带有稀疏索引字段的记录,这足以让我们处理架构更改。
请看下面的合集
Collection marks
{_id:1, sub1: 67, sub2: 78, sub3: 56, total: 201}
{_id:2, sub1: 60, sub2: 70, sub3: 50, total: 180}
{_id:3, sub1: 80, sub2: 70, sub3: 50}
Create sparse index
db.marks.createIndex( { total: 1 } , { sparse: true, unique: true } )
db.marks.find().sort( { total: -1 } )
This query will return all the 3 records, we have applied sort on the sparse indexed field, but MongoDB will not select the sparse index to fulfill the query in order to return complete results.
db.marks.find().sort( { total: -1 } ).hint( { total: 1 } ), this query will return only 2 records, those who are having the total, so to use the sparse index, explicitly specify the index with hint()
参考文献
https://docs.mongodb.com/manual/core/index-sparse/
https://docs.mongodb.com/manual/core/index-sparse/#sparse-index-incomplete-results
希望对你有帮助!