Dynamically create index with mongoid

2020-06-03 04:30发布

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?

1条回答
SAY GOODBYE
2楼-- · 2020-06-03 05:04

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)

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)

Thanks to js_ for noting this change.

查看更多
登录 后发表回答