Ruby 在mongodb中插入哈希。删除未使用的密钥

Ruby 在mongodb中插入哈希。删除未使用的密钥,ruby,mongodb,mongoid,upsert,Ruby,Mongodb,Mongoid,Upsert,: 如果指定多个字段值对,$set将更新或创建 每个领域 我有这样一个mongoid文档: class MyCounter include Mongoid::Document field :date, type: Date field :properties, type: Hash end hash = {properties.0 => 50, properties.1 => 100 } MyCounter.where(something).find_and_modi

:

如果指定多个字段值对,$set将更新或创建 每个领域

我有这样一个mongoid文档:

class MyCounter
  include Mongoid::Document

  field :date, type: Date
  field :properties, type: Hash
end
hash = {properties.0 => 50, properties.1 => 100 }
MyCounter.where(something).find_and_modify(
    { '$set' => hash, {'upsert' => 'true', new: true}
)
当我尝试更改如下属性时:

class MyCounter
  include Mongoid::Document

  field :date, type: Date
  field :properties, type: Hash
end
hash = {properties.0 => 50, properties.1 => 100 }
MyCounter.where(something).find_and_modify(
    { '$set' => hash, {'upsert' => 'true', new: true}
)
它将旧密钥保留在属性哈希上

完全替换文档中的哈希(如果不存在,则创建新文档)的正确方法是什么

编辑

我现在正在做这件蠢事:

MyCounter.where(
  date: date
).find_and_modify(
  { '$unset' => { properties: nil} }, {'upsert' => 'true', new: true}
)

MyCounter.where(
  date: date
).find_and_modify(
  { '$set' => hash }, {'upsert' => 'true', new: true}
)

只是不要使用$set。仅通过传递
field:value
对,将替换所有字段(除了_id字段)

这应该行得通

MyCounter.where(
  date: date
).find_and_modify(
  hash, {'upsert' => 'true', new: true}
)

未使用对您意味着什么?当然,如果你希望得到你现在所期望的“整个”对象结构,那么就替换它。@NeilLunn如果属性是{a:100,b:200},新值是{b:500,c:600},我以{a:100,b:500,c:600}结尾。我不需要“a”键。如果没有$set if,则会出现以下错误:失败,出现错误57:“异常:'properties.0'中的虚线字段'properties.0'对于存储无效。您可能无法使用点表示法替换完整文档。请尽量不要像这样使用点表示法:
{properties:{'0'=>“”}