LoginSignup
2
2

More than 5 years have passed since last update.

Mongo[DB|id]-1系でオートインクリメント

Last updated at Posted at 2013-07-25

find_and_modify を Mongoid から使いたいんだけど、最新のドキュメント通りだと上手く行かなくて(当たり前)、古い MongoDB と Mongoid でオートインクリメントしたい時の話。

auto_inc.rb
gem 'bson', '1.0.9'
require 'bson'
gem 'mongoid', '1.9.2'
require 'mongoid'

class Sequence
  include Mongoid::Document
  store_in :sequences
  field :collection_name
  field :seqid,:type=>Integer
  index :seqid, :unique=>true
end

class User
  include Mongoid::Document
  store_in :users
  field :user_id, :type => Integer
  field :name
  field :age, :type => Integer
  field :created_at,:type => Time
  field :updated_at,:type => Time

  before_create :set_seq

  private
  def set_seq
    self.user_id = Mongoid.master.collection("sequences").find_and_modify( :query => { "collection_name" => "users" }, :update => { "$inc" => { "seqid" => 1 } }, :new => true )["seqid"]
  end
end

って定義しといてからオートインクリメントしたいコレクションのレコード作っとく。

Sequence.create!(:collection_name => "users", :seqid => 0)

後はなんも考えずに

User.create!(:name => "hoge", :age => 31)

って感じで。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2