Ruby on rails Ruby/Mongoid-如何增加集合中的值并返回新值
我正在更新一些RubyonRails代码,这些代码使用了一个非常过时的Mongoid版本。我有以下代码行,它获取集合中的第一个文档,并将字段Ruby on rails Ruby/Mongoid-如何增加集合中的值并返回新值,ruby-on-rails,ruby,mongodb,mongoid,Ruby On Rails,Ruby,Mongodb,Mongoid,我正在更新一些RubyonRails代码,这些代码使用了一个非常过时的Mongoid版本。我有以下代码行,它获取集合中的第一个文档,并将字段nextid增加1,然后返回新值: surveyid=surveyid.first.safety.inc(:nextid,1) 我已经将Mongoid更新到版本6.0.3,它没有安全的方法。如果我只是使用: surveyid=surveyid.first.inc(:nextid,1) 它可以工作,但是inc不返回任何内容,我也不知道新值是什么 新的Mongo
nextid
增加1,然后返回新值:
surveyid=surveyid.first.safety.inc(:nextid,1)
我已经将Mongoid更新到版本6.0.3,它没有安全的方法。如果我只是使用:
surveyid=surveyid.first.inc(:nextid,1)
它可以工作,但是inc
不返回任何内容,我也不知道新值是什么
新的Mongoid版本中的等效代码是什么?谢谢 您可以像这样检索值
surveyid = SurveyId.first.inc(:nextid, 1).nextid
我弄明白了。我发现了一颗宝石,它完全符合我的要求
现在,我可以向我的集合中添加一个自动递增字段,并完成它。此外,这个Gem的示例说明了如何增加一个值并获得新的值,尽管我并没有深入研究它,因为我只是决定使用Gem:
def inc
if defined?(::Mongoid::VERSION) && ::Mongoid::VERSION >= '5'
collection.find(query).find_one_and_update({ '$inc' => { number: @step } }, new: true, upsert: true, return_document: :after)['number']
elsif defined?(::Mongoid::VERSION) && ::Mongoid::VERSION >= '3'
collection.find(query).modify({ '$inc' => { number: @step } }, new: true, upsert: true)['number']
else
opts = {
"query" => query,
"update" => {"$inc" => { "number" => @step }},
"new" => true # return the modified document
}
collection.find_and_modify(opts)["number"]
end
end