OR查询匹配nil或“”与Mongoid仍匹配“”?

时间:2012-03-09 22:37:21

标签: ruby-on-rails-3 mongodb mongoid

我正在尝试为嵌入式Mongoid :: Document编写一个查询,该查询找到“address”字段既不是nil也不是“”的任何记录。

使用MongoDB文档,this issue in the Mongoid bug reports和Mongoid文档的组合,我认为这样的事情应该有效:

scope :with_address, where("$or" => [{:address => {"$ne" => nil}}, {:address => {"$ne" => ""}}])

当我运行它时,选择器看起来没问题:

1.9.2p290 :002 > report.document.records.with_address
 => #<Mongoid::Criteria
  selector: {"$or"=>[{:address=>{"$ne"=>nil}}, {:address=>{"$ne"=>""}}]},  
  options:  {},
  class:    GlobalBoarding::MerchantPrincipal,
  embedded: true>

但是当我查看结果时,它们包含一个空白地址的条目:

1.9.2p290 :007 > report.document.records.with_address.last  
<Record _id: 4f593f245af0501074000122, _type: nil,  version: 1, name: "principal contact 3", title: "", dob: nil, address: "", email: "", phone: "", fax: ""> 

我无法弄清楚我是否在查询错误,如果这是Mongoid的错误,或者是否存在其他问题。有没有人有这样的查询经验?

2 个答案:

答案 0 :(得分:4)

最后,这是我能找到的唯一方法,可以选择某个字段不是nil而不是空白的记录:

scope :with_name, all_of(:name.ne => nil).all_of(:name.ne => "")

答案 1 :(得分:2)

我想你会对此轻笑。

nil和“”都不同于: 不是,而不是“”。

你的意思是and,而且可以在没有$and的情况下表达,只使用:{/ p>

$ne=>nil, $ne=>""