【问题标题】:Dynamically create index with mongoid使用 mongoid 动态创建索引
【发布时间】:2020-06-10 07:23:22
【问题描述】:

我有一个为我的文档创建新字段的工作,我想在这个工作结束时为这些字段创建索引。 我试过了

Model.index("field"=>-1)

还有

Mongoid::Sessions.default[:rating_prediction].ensureIndex

没有成功

这可能吗?

【问题讨论】:

    标签: ruby mongodb mongoid


    【解决方案1】:

    Model.index(:field => -1),或多或少只是用Model注册索引的存在,它实际上并没有创建索引。你在找create_indexes:

    - (true) <b>create_indexes</b>

    将实际的索引创建 cmets 发送到 MongoDB 驱动程序

    所以你想说:

    Model.index(field: -1)
    Model.create_indexes
    

    您也可以通过 Moped 直接创建它们,方法是在集合的 indexes 上调用 create

    Mongoid::Sessions.default[:models].indexes.create(field: -1)
    Model.collection.indexes.create(field: 1)
    # or in newer versions:
    Model.collection.indexes.create_one(field: 1)
    

    Mongoid::Sessions 在较新版本中已重命名为 Mongoid::Clients,因此您可能需要说:

    Mongoid::Clients.default[:models].indexes.create(field: 1)
    Model.collection.indexes.create(field: 1)
    # or in even newer versions:
    Model.collection.indexes.create_one(field: 1)
    

    感谢js_mltsy 注意到这些变化。

    【讨论】:

    • 供将来参考 Mongoid::Sessions 现在称为 Mongoid::Clients
    • @js_ 感谢您告诉我。
    • 该方法现在称为create_one,以便在Mongoid中动态创建唯一的复合索引:Model.collection.indexes.create_one({field: 1, another_field: 1}, {unique: true})
    • @mltsy 喜欢更新的版本?我不再使用 MongoDB 做任何事情,所以我很难检查。
    • 抱歉回复晚了。我不确定它是什么时候改变的——据我所知,自从 Mongodb 2.0 以来它一直是create_one:api.mongodb.com/ruby/2.0.6/Mongo/Index/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 2016-03-23
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多