【问题标题】:mongoid query collection where two columns are equal to each othermongoid 查询集合,其中两列彼此相等
【发布时间】:2013-08-30 11:51:41
【问题描述】:

我正在使用 Mongoid 连接到 mongodb,需要查询帮助。

我有一个 Parent 模型,其中每个父母和孩子都有一个名字。

Class Parent
  field: :name
  field: :child_name
end

我可以将孩子分成另一个模型和/或嵌入它,但我的数据库需求很简单。我想查询所有子名与父名相同的文档。 (例如,父亲是 Jeff,儿子也是 Jeff)。

尝试了以下方法,但它不起作用。

  parent = Parent.where(name: :child_name)

不确定如何使用 Mongoid。非常感谢任何帮助

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

    如果您向 Mongoid 的 where() 提供一个字符串,它假定您使用的是 JavaScript,并触发 MongoDB 的原生 $where,这正是您所需要的:

    Parent.where("this.name == this.child_name")

    【讨论】:

    • 这很有帮助!你有没有机会知道如何包含一个附加条款?我想添加“AND this.active = t”,但它给了我错误。
    猜你喜欢
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 2018-08-31
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多