在 Mongoid 中使用集合级操作 [英] Using collection-level operations in Mongoid

查看:45
本文介绍了在 Mongoid 中使用集合级操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试验 Ruby(我不太了解)和 Mongo(我了解它).我制作了一个带有 :accessed 字段的 Mongoid 模型.我知道在 Mongo 中我可以运行类似的东西:

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}}
})

但是当我在 Mongoid 中运行 MyModel.collection.find_and_modify 时,我得到了一个哈希值.有没有办法可以将其强制转换为我的模型类的实例,或者在 Mongoid 中执行更好的支持查询?

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?

推荐答案

默认 find_and_modify 返回哈希值,查看 文档

By default find_and_modify returns the hash, check the documentation

参数:

  • opts (Hash)(默认为:{})——一组可定制的选项

选项哈希(选项):

  • :query (Hash) — 默认值:{} — 用于匹配的查询选择器文档所需的文件.
  • :update (Hash) — 默认值:nil — 要对匹配的文档执行的更新操作.
  • :sort (Array, String, OrderedHash) — 默认值:{} — 使用 Cursor#sort 可用的任何排序选项为查询指定排序选项.如果查询将匹配多个文档,排序顺序很重要,因为只会更新和返回第一个匹配的文档.
  • :remove (Boolean) — 默认值:false — 如果为 true,则从集合中移除返回的文档.
  • :new (Boolean) — 默认值:false — 如果为 true,则返回更新的文档;否则,返回更新前的文档.

退货:

  • (Hash) — 匹配的文档.

但是您可以通过将散列作为参数传递来简单地初始化模型,从而将散列转换为您的集合对象

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

现在您可以对转换后的对象应用任何 mongoid 操作.它将完美运行.

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

希望能帮到你

这篇关于在 Mongoid 中使用集合级操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆