Dynamically create index with mongoid

后端 未结 1 1809
广开言路
广开言路 2021-02-07 23:56

I have a job that create new fields to my document, I want, at the end of this job, to create indexes to this fields. I tried

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


        
相关标签:
1条回答
  • 2021-02-08 00:24

    Saying Model.index(:field => -1), more or less, just registers the existence of the index with Model, it doesn't actually create an index. You're looking for create_indexes:

    - (true) create_indexes

    Send the actual index creation comments to the MongoDB driver

    So you'd want to say:

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

    You can also create them directly through Moped by calling create on the collection's indexes:

    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 has been renamed to Mongoid::Clients in newer versions so you might need to say:

    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)
    

    Thanks to js_ and mltsy for noting these changes.

    0 讨论(0)
提交回复
热议问题