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)
and also
Mongoid::Sessions.default[:rating_prediction].ensureIndex
Without success
Is this possible?
You can check out this page for Mongoid v3.x if you haven't upgraded yet. You can define indexes on documents using the index macro. Provide the key for the index along with a direction. For additional options, supply them in a second options hash parameter. You can define indexes on embedded document fields as well.
MongoDB indexes use a B-tree data structure. The default name for an index is the concatenation of the indexed keys and each key's direction in the index ( i.e. 1 or -1) using underscores as a separator. For example, an index created on { item : 1, quantity: -1 } has the name item_1_quantity_-1.
If you index a field that holds an array value, MongoDB creates separate index entries for every element of the array. These multikey indexes allow queries to select documents that contain arrays by matching on element or elements of the arrays.
The collation applies only to the index keys with string values. The collation applies to the indexed keys whose values are string. For queries or sort operations on the indexed keys that uses the same collation rules, MongoDB can use the index. For details, see Collation and Index Use. New in version 4.2.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With