Using collection-level operations in Mongoid

徘徊边缘 提交于 2019-12-25 01:06:36

问题


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?


回答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



来源:https://stackoverflow.com/questions/8380874/using-collection-level-operations-in-mongoid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!