简体   繁体   中英

Ruby / Mongoid - How to increment a value in a collection and return the new value

I'm updating some Ruby on Rails code that uses a pretty outdated version of Mongoid. I have the following line of code which gets the first document in a collection and increments the field nextid by 1, then returns the new value:

surveyid = SurveyId.first.safely.inc(:nextid, 1)

I've updated Mongoid to version 6.0.3, which no longet has a safely method. If I just use:

surveyid = SurveyId.first.inc(:nextid, 1)

It works, but inc doesn't return anything and I have no idea what the new value is.

What's the equivalent code in newer Mongoid versions? Thanks!

您可以像这样检索值。

 surveyid = SurveyId.first.inc(:nextid, 1).nextid

I got this figured out. I found a gem that does exactly what I want called mongoid_auto_increment .

Now I can just add an auto-incrementing field to my collection and be done with it. Also, the source code for this Gem illustrates how to increment a value and get the new value, though I didn't really dig into it too much since I just decided to use the gem instead:

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM