【问题标题】:Querying an array field that contains hashes in mongoid在 mongoid 中查询包含哈希的数组字段
【发布时间】:2013-03-14 12:35:49
【问题描述】:

我有一个这样的模型

class User
  include Mongoid::Document
  field :c, as: :categories, type: Array
end

我在上面存储信息是这样的:

a = UserCheckin.new
a.c = [{id: rand(1000), name: 'a'}, {id: rand(1000), name: 'b'}, {id: rand(1000), name: 'c'}]
a.save

我不知道我是否通过在其上存储哈希来滥用数组类型,但问题是 mongodb 并没有抱怨它。

如何查询类别名称为“a”或类别 ID 大于 2 的用户之类的内容?

提前致谢,

【问题讨论】:

    标签: ruby-on-rails ruby mongodb mongoid


    【解决方案1】:

    我似乎找到了答案...对于剩下的人,我会在这里发布。

    User.where(c: {'$elemMatch' => {name: 'a'}})
    

    它将返回所有用户,其类别数组中包含一个或多个名称为“a”的元素。

    【讨论】:

      猜你喜欢
      • 2011-05-13
      • 2017-04-16
      • 2015-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多