Ild*_*dar 2 ruby mongodb mongoid
我需要选择与给定事务具有相同类型的事务.我需要检查它是否没有返回所有nil类型的事务.
使用ActiveRecord,我可以轻松编写:
given_transaction = Transaction.first
needed_transactions = Transaction.where('type != nil and type = ?', given_transaction.type)
Run Code Online (Sandbox Code Playgroud)
和所有的作品
当我尝试用mongoid写同样的东西时:
needed_transactions = Transaction.where(:type => given_transaction.type, :type.ne => nil)
Run Code Online (Sandbox Code Playgroud)
它生成以下查询:
"query"=>{:type=>{"$ne"=>"planned"}}
Run Code Online (Sandbox Code Playgroud)
换句话说,mongoid忽略第一次检查并仅使用对该字段的最后一次检查.
我尝试了"all_of","all_in","和" - 但仍然无法找到有效的解决方案.
也许我做错了什么......因为这个......我的世界正在颠倒...... :(((
从精细手册:
Mongoid中的所有查询都是Criteria,它是MongoDB动态查询的可链接且延迟评估的包装器.
查看Criteria文档,where我们看到一堆具有单一条件的示例.但请记住上面提到的可链接性.也许你正在寻找这个:
needed_transactions = Transaction.where(:type => given_transaction.type).where(:type.ne => nil)
Run Code Online (Sandbox Code Playgroud)
该Criteria#and文档可能会好好读书,以及:
添加另一个必须匹配的简单表达式才能返回结果.这
Criteria#where与语法糖相同,并且主要用于语法糖.Run Code Online (Sandbox Code Playgroud)MONGOID # Match all people with last name Jordan and first name starting with d. Person.where(last_name: "Jordan").and(first_name: /^d/i) MONGODB QUERY SELECTOR { "last_name" : "Jordan", "first_name" : /^d/i }
我不得不承认,我不明白你为什么要这样检查:type两次呢; 如果given_transaction.type.nil?可能,那么你甚至可以在不查询数据库的情况下处理它.
顺便说一下,有了ActiveRecord,你想说这个:
Transaction.where('type is not null and type = ?', given_transaction.type)
Run Code Online (Sandbox Code Playgroud)
就你所得到的奇怪查询而言,当你这样做时:
Transaction.where(:type => given_transaction.type, :type.ne => nil)
Run Code Online (Sandbox Code Playgroud)
Mongoid最终尝试使用两个值为:type密钥构建一个Hash :
{ :type => 'planned' }
{ :type => { :$ne => nil } }
Run Code Online (Sandbox Code Playgroud)
不知何故它最终取代了nil用'planned'.我不知道Mongoid的内部细节where或它补充到Symbol中的方法,我只是从观察到的行为中回溯.