使用mongoid动态创建索引

2024-05-12

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

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

and also

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

没有成功

这可能吗?


Saying Model.index(:field => -1) http://rubydoc.info/github/mongoid/mongoid/Mongoid/Indexable/ClassMethods:index,或多或少,只是注册索引的存在Model,它实际上并不创建索引。您正在寻找create_indexes http://rubydoc.info/github/mongoid/mongoid/Mongoid/Indexable/ClassMethods:create_indexes:

- (true) create_indexes

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

所以你想说:

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

您还可以通过调用 Moped 直接创建它们create http://rubydoc.info/github/mongoid/moped/Moped/Indexes:create关于集合的indexes http://rubydoc.info/github/mongoid/moped/Moped/Collection: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已更名为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_ https://stackoverflow.com/users/2492795/js and mltsy https://stackoverflow.com/users/79079/mltsy注意到这些变化。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用mongoid动态创建索引 的相关文章

随机推荐