0

From the Mongo documentation:

If you specify multiple field-value pairs, $set will update or create each field.

I have a mongoid document like this:

class MyCounter
  include Mongoid::Document

  field :date, type: Date
  field :properties, type: Hash
end

and when I try to change the properties like this:

hash = {properties.0 => 50, properties.1 => 100 }
MyCounter.where(something).find_and_modify(
    { '$set' => hash, {'upsert' => 'true', new: true}
)

it keeps the old keys on the property hash.

What's the correct way to completely replace (and create a new document if it doesn't exist) an hash in a document?

EDIT

I'm currently doing this which is dumb:

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}
)
dcarneiro
  • 7,060
  • 11
  • 51
  • 74
  • What does "unused" mean to you? Surely if you expect to have the "whole" object structure as you expect it to be right now then just replace it. – Neil Lunn Mar 06 '15 at 12:55
  • @NeilLunn If properties is {a: 100, b: 200} and the new value is {b: 500, c: 600 } I ended with {a: 100, b: 500, c: 600 }. I don't want the "a" key. – dcarneiro Mar 06 '15 at 14:08

1 Answers1

0

Just don't use $set. By only passing field: value pairs all the fields are replaced (except the _id field)

This should work fine.

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

http://docs.mongodb.org/manual/reference/method/db.collection.update/#example-update-replace-fields

Ismael Abreu
  • 16,443
  • 6
  • 61
  • 75
  • Without the $set if gives the following error: failed with error 57: "exception: The dotted field 'properties.0' in 'properties.0' is not valid for storage. – dcarneiro Mar 09 '15 at 12:25
  • You probably can't use dot notation for full document replacements. Try to not use the dot notation like this: `{properties: { '0' => "" }}` – Ismael Abreu Mar 09 '15 at 15:33