I need to update some data in the MongoDB if data already exists, if not to upsert or create record with this data. My models are:
class Garage
include Mongoid::Document
include Mongoid::Attributes::Dynamic
has_many :cars
end
class Car
include Mongoid::Document
include Mongoid::Attributes::Dynamic
belongs_to :garage
index({ car_make: 1, plate_number: 1 }, { sparse: true, unique: true, drop_dups: true })
end
Then I have this query
Garage.cars.collecttion.find(:car_make => "Ford", :plate_number =>"12x234")
.update(:car_make => "Ford", :plate_number =>"12x234", :car_colour=>"red", :year_make="2012", {upsert: true})
But this query does not add Garage _id
to cars
so it does not work correctly.
I also tried another query:
Garage.cars.where(:car_make => "Ford", :plate_number =>"12x234")
.update(:car_make => "Ford", :plate_number =>"12x234", :car_colour=>"red", :year_make="2012")
But it does not take {upsert: true}
option, so it does not create a record if it does not exist yet!
Then I tried this:
Garage.cars.where(:car_make => "Ford", :plate_number =>"12x234")
.find_and_modify(:car_make => "Ford", :plate_number =>"12x234", :car_colour=>"red", :year_make="2012", {upsert: true})
Geting error:
failed with error 11000: "exception: insertDocument :: caused by :: 11000 E11000 duplicate key
Does anybody knows how to fix it? Thank you very much for the help!