【问题标题】:Mongodb apply model changes without dropping the collectionMongodb 应用模型更改而不删除集合
【发布时间】:2016-10-25 10:30:55
【问题描述】:

每次我对架构进行更改时,就像我添加唯一索引或为字段设置“sparse: true”一样,我必须删除集合才能应用更改。这对我来说在生产服务器中是不可能的。有没有其他方法可以将更改应用于集合而不删除它?我是 mongodb 的新手。由于我使用的是 mlab,因此我也无法重新启动 mongo 服务。请帮我解决这个问题。

注意:我使用的是 nodejs 版本 4.2.0、mongoose 4.4.7、mongodb 3.2.9(我使用的是 mlab)。

【问题讨论】:

  • 什么意思,添加唯一索引或设置稀疏时需要删除集合?那是 100% 错误的。
  • 您能否提供您用于应用此索引的代码。您当然不需要为了应用索引而删除您的集合
  • 如果您的索引字段存在于新文档中,我认为您不需要为此删除整个集合。可以分享新旧文件吗?

标签: node.js mongodb unique-index mlab


【解决方案1】:

当架构发生变化时,无需删除集合并重新创建它。

更多信息:

稀疏索引仅包含具有索引字段的文档的条目,即使索引字段包含空值。索引会跳过任何缺少索引字段的文档。索引是“稀疏的”,因为它不包括集合的所有文档。相比之下,非稀疏索引包含集合中的所有文档,为那些不包含索引字段的文档存储空值。

稀疏索引和不完整结果

如果稀疏索引会导致查询和排序操作的结果集不完整,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

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2020-11-29
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    相关资源
    最近更新 更多