Brian Hicks
Brian Hicks

Reputation: 6413

Using collection-level operations in Mongoid

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?

Upvotes: 0

Views: 1355

Answers (1)

RameshVel
RameshVel

Reputation: 65887

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

Upvotes: 1

Related Questions