或与查询匹配零或“”与Mongoid仍匹配“”?
我想为嵌入式Mongoid :: Document编写一个查询,查找其中“地址”字段既不是零也不是“”的任何记录。或与查询匹配零或“”与Mongoid仍匹配“”?
使用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的错误,或者是否有其他问题。有没有人有这样的查询经验?
,这是我能找到的唯一途径,致力于选择的记录,其中某一个领域是不是零和非空白:
scope :with_name, all_of(:name.ne => nil).all_of(:name.ne => "")
我想你会在这个笑声。
“nil”和“”与不一样,也不是“”。
你真正的意思and
,并且在不$and
来表达,只用:
$ne=>nil, $ne=>""
你是指这里的mongoid语法,还是mongo?试着从你的建议推断,我已经在mongoid中尝试了这两个:where(:name.ne => nil,:name.ne =>“”),其中(:address => {“$ ne”=>“ “,”$ ne“=>无})。在这两种情况下,mongoid似乎都在破坏标准,所以前者最终以{:name => {“$ ne”=>“”}}作为选择器,后者以{:address =>结束{“$ ne”=> nil}} – kclair 2012-03-09 23:43:32
对不起,是的,mongo语法是: {address:{$ ne:null},address:{$ ne:“”}} – 2012-03-10 00:07:34
看起来像排除是正确的在mongoid中做? Model.excludes(地址:nil,地址:“”) - 或者可能不是,因为它是一个嵌入式文档... – 2012-03-10 00:12:14
不应该查询使用'$和'而不是'$或'? – Dieseltime 2012-03-09 22:52:32
不,那永远不会匹配?如果该值为零,则它将不匹配“”,反之亦然。 – kclair 2012-03-09 22:56:58
我同意,你或没有意义。它是布尔逻辑,a!= 1或!= 2将始终返回true,因为它总是不会是1或不是2. – 2012-03-09 23:04:10