2

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!

arthur-net
  • 1,138
  • 1
  • 13
  • 34

1 Answers1

1
Garage.cars.where(:car_make => "Ford", :plate_number =>"12x234").upsert(:car_make => "Ford", :plate_number =>"12x234", :car_colour=>"red", :year_make="2012")

Try this..not sure if this will work

Sooraj Chandu
  • 1,348
  • 16
  • 35
  • Try to save the query object to a variable and then call the upsert on the saved object – Sooraj Chandu Oct 15 '14 at 12:13
  • I tried but it works very very slow, `Garage.cars.collection.find.... `works x100 times quicker but not assigning relations between `Garage and cars` Any ideas why? Anyway thank you for trying to help me! – arthur-net Oct 15 '14 at 14:04
  • Need to check on that..might be because the count of objects in the collection is too big.. – Sooraj Chandu Oct 28 '14 at 06:24