如果数据已经存在,我需要更新 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 _id
添加到 cars
所以它不能正常工作。
我还尝试了另一个查询:
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
有人知道怎么解决吗?非常感谢你的帮助!
最佳答案
Garage.cars.where(:car_make => "Ford", :plate_number =>"12x234").upsert(:car_make => "Ford", :plate_number =>"12x234", :car_colour=>"red", :year_make="2012")
试试这个..不确定这是否有效
关于ruby-on-rails - 如何使用 Ruby Mongoid Moped 更新插入选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26381162/