0

I'm experimenting with Ruby (which I don't know very well) and Mongo (which I do.) I've made a Mongoid model with an :accessed field. I know that in Mongo I can just run something like:

data = db.collection.findAndModify({
  query: { ... },
  update: {$inc: {accessed: 1}}
})

But when I run MyModel.collection.find_and_modify in Mongoid, I get back what appears to be a hash. Is there a way I can coerce this into an instance of my model class, or do a better supported query in Mongoid?

Brian Hicks
  • 6,213
  • 8
  • 51
  • 77

1 Answers1

1

By default find_and_modify returns the hash, check the documentation

Parameters:

  • opts (Hash) (defaults to: {}) — a customizable set of options

Options Hash (opts):

  • :query (Hash) — default: {} — a query selector document for matching the desired document.
  • :update (Hash) — default: nil — the update operation to perform on the matched document.
  • :sort (Array, String, OrderedHash) — default: {} — specify a sort option for the query using any of the sort options available for Cursor#sort. Sort order is important if the query will be matching multiple documents since only the first matching document will be updated and returned.
  • :remove (Boolean) — default: false — If true, removes the the returned document from the collection.
  • :new (Boolean) — default: false — If true, returns the updated document; otherwise, returns the document prior to update.

Returns:

  • (Hash) — the matched document.

But you can convert the hash to your collection object by simply initializing the model by passing the hash as a argument

 >> x = MyModel.collection.find_and_modify(:query => {...},:update => {...})
 >> x.class
 >> BSON::OrderedHash
 >> obj = MyModel.new(x)
 >> obj.class
 >> MyModel

And now you can apply any mongoid operation on the converted object. It will work perfectly.

Hope it helps

RameshVel
  • 64,778
  • 30
  • 169
  • 213
  • Hi there, I'm using both Mongoid and collection level operations to manipulate my mongodb, but some how I'm not able to create, save or update my database using the mongoid active record operations like Model.save, Model.update_attributes,etc. Can you please suggest any solutions? – Niral Munjariya Oct 29 '14 at 09:38