OR query matching nil or “” with Mongoid still matches “”?

无人久伴 提交于 2019-12-24 01:59:36

问题


I'm trying to write a query for an embedded Mongoid::Document which finds any record where the "address" field is neither nil nor "".

Using a combination of the MongoDB documentation, this issue in the Mongoid bug reports, and the Mongoid documentation, I think that something like this should work:

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

When I run this, the selector looks ok:

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

But when I look at the results, they contain an entry with a blank address:

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: ""> 

I can't figure out if I'm doing a query wrong, if this is a bug with Mongoid, or if there is some other issue. Does anyone have experience with such a query?


回答1:


in the end, this is the only way i could find that works to select records where a certain field is not nil and not blank:

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



回答2:


I think you're going to chuckle at this.

Neither nil nor "" is the same as saying: Not nil and not "".

You really mean and, and that can be expressed without $and, using just:

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


来源:https://stackoverflow.com/questions/9641924/or-query-matching-nil-or-with-mongoid-still-matches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!