或查询匹配nil或“"的查询与Mongoid仍然匹配“"? [英] OR query matching nil or "" with Mongoid still matches ""?
问题描述
我正在尝试为嵌入式Mongoid :: Document编写查询,以查找"address"字段既不是nil也不是"的任何记录.
I'm trying to write a query for an embedded Mongoid::Document which finds any record where the "address" field is neither nil nor "".
结合使用MongoDB文档 Mongoid错误报告中的此问题,和Mongoid文档,我认为类似的东西应该可以工作:
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: "">
我无法确定我在执行错误的查询,这是Mongoid的错误还是其他问题.有没有人有过这样的查询经验?
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?
推荐答案
,这是我发现选择某些字段不是nil且不是空白的记录的唯一方法:
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 => "")
这篇关于或查询匹配nil或“"的查询与Mongoid仍然匹配“"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!