2

如果数据已经存在,我需要更新 MongoDB 中的一些数据,如果不更新或使用这些数据创建记录。我的模型是:

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

得到错误:

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

有人知道如何解决吗?非常感谢你的帮助!

4

1 回答 1

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

试试这个..不确定这是否可行

于 2014-10-15T11:25:44.687 回答