OR query matching nil or “” with Mongoid still mat

2019-07-19 18:33发布

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?

2条回答
Fickle 薄情
2楼-- · 2019-07-19 19:06

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 => "")
查看更多
Summer. ? 凉城
3楼-- · 2019-07-19 19:16

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=>""
查看更多
登录 后发表回答