2014-10-15 1 views
2

데이터가 이미 존재하는 경우 MongoDB의 일부 데이터를 업데이트해야합니다.이 데이터로 업서 트하거나 레코드를 만들지는 않습니다. 내 모델은 다음과 같습니다 Ruby Mongoid Moped upsert 옵션으로 업데이트하는 방법

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 

은 그 때 나는이 쿼리

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}) 

을하지만이 쿼리는 그래서 제대로 작동하지 않습니다 Garage _idcars에 추가하지 않습니다. 는 또한 다른 쿼리 시도 :

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

를하지만 아직 존재하지 않는 경우가 레코드를 생성하지 않도록 그것은 {upsert: true} 옵션을 고려하지 않습니다!

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 오류 :

failed with error 11000: "exception: insertDocument :: caused by :: 11000 E11000 duplicate key 

아무도 그것을 해결하는 방법을 알고 있습니까 은 그 때 나는이 시도? 도움 주셔서 대단히 감사합니다! 이

답변

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

는 this..not 있는지보십시오.
+0

이 아니, 작동하지 않는 작동하는지 –

+0

쿼리 개체를 변수에 저장 한 다음 저장된 개체에 대해 upsert를 호출하려고 시도했습니다. –

+0

시도했지만 작동 속도가 매우 느 렸습니다. 'Garage.cars.collection.find ....'는 x100 배 더 빠르지 만 관계를 지정하지 않습니다 차고와 차 사이에 어떤 아이디어가 있니? 어쨌든 도와 줘서 고마워! –