【问题标题】:How to use $in operator in embed document如何在嵌入文档中使用 $in 运算符
【发布时间】:2014-05-10 06:29:06
【问题描述】:

我是 MongoID 的新手。我有以下型号:

class Vehicle
  include Mongoid::Document
  include Mongoid::Timestamps

  ##
  # Relationship
  embeds_one  :specification
end

class Specification
  include Mongoid::Document

  ##
  # Columns
  field :body,            type: String

  ##
  # Relationship
  embedded_in :vehicle

end

在我的控制器中,我尝试在 bodyspecification /embed document/ 字段中使用 $in 运算符。如何在嵌入文档中使用$in 运算符?我尝试了下面的代码,但它不起作用。

result += Vehicle.where(:specification.matches => { :body.in => param(:body) }) if params[:body].present?

感谢您的帮助:)

【问题讨论】:

  • 我不确定你想在这里做什么,但embeds_one 只是一堆嵌入哈希的包装,所以Vehicle.where('specification.body' => ...) 可能是一个起点。

标签: ruby-on-rails mongodb ruby-on-rails-4 mongoid mongoid3


【解决方案1】:

正如@mu-is-too-short 在他的评论中提到的那样,在您使用的嵌入式文档中进行搜索

if params[:body].present?
  result += Vehicle.where('specification.body' => param(:body)).to_a
end

请注意Vehicle.where(...) 返回的Criteria 不是对象,只是要评估的查询。

还请注意,如果您想使用特定的运算符,例如 in<<=,则必须使用相应的 mongodb 运算符

Vehicle.where('specification.body' => {'$in' => param(:body)})  # matches .in
Vehicle.where('specification.body' => {'$lt' => param(:body)})  # matches <
Vehicle.where('specification.body' => {'$lte' => param(:body)}) # matches <=

【讨论】:

  • 你好@artmees,非常感谢。它就像一个魅力:D
猜你喜欢
  • 1970-01-01
  • 2018-09-16
  • 2022-01-01
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
相关资源
最近更新 更多