Ruby Mongoid:对单个字段进行多个检查

Ruby Mongoid:对单个字段进行多个检查,ruby,mongodb,mongoid,Ruby,Mongodb,Mongoid,我需要选择与给定事务类型相同的事务。我需要检查它是否返回nil类型的所有事务 使用ActiveRecord,我可以轻松编写: given_transaction = Transaction.first needed_transactions = Transaction.where('type != nil and type = ?', given_transaction.type) 和所有的工作 当我试图用mongoid写同样的东西时: needed_transactions = Transa

我需要选择与给定事务类型相同的事务。我需要检查它是否返回nil类型的所有事务

使用ActiveRecord,我可以轻松编写:

given_transaction = Transaction.first
needed_transactions = Transaction.where('type != nil and type = ?', given_transaction.type)
和所有的工作

当我试图用mongoid写同样的东西时:

needed_transactions = Transaction.where(:type => given_transaction.type, :type.ne => nil)
它生成以下查询:

"query"=>{:type=>{"$ne"=>"planned"}}
换句话说,mongoid忽略第一个检查,只对字段使用最后一个检查

我尝试了所有的,所有的,和-仍然找不到有效的解决方案

也许我做错了什么。。。因为这个,我的世界变得天翻地覆

来自:

Mongoid中的所有查询都是条件,它是MongoDB动态查询的可链接且延迟计算的包装器

看看我们看到的一系列例子,只有一个条件。但请记住上面提到的可链接性。也许你正在寻找这个:

needed_transactions = Transaction.where(:type => given_transaction.type).where(:type.ne => nil)
这些文档也可能是很好的读物:

添加另一个必须匹配才能返回结果的简单表达式。这与Criteriawhere相同,主要用于语法糖

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 }
我不得不承认,我不明白你为什么要检查:尽管这样打两次;如果给定_transaction.type.nil?这是可能的,那么您甚至不需要查询数据库就可以处理它

顺便说一句,有了ActiveRecord,你会想说:

Transaction.where('type is not null and type = ?', given_transaction.type)
就您收到的奇怪查询而言,当您执行此操作时:

Transaction.where(:type => given_transaction.type, :type.ne => nil)
Mongoid最终尝试为:type键构建两个值的哈希:


不知何故,它最终以“计划”取代了零。我不知道Mongoid的where的内部细节,也不知道它修补到Symbol的方法,我只是从观察到的行为中回溯。

Transaction.where:type=>bla',:type.ne=>nil导致错误“NoMethodError:undefined method merge!”!对于bla:String'.hm:local>>Transaction.where:type=>'bla'.and:type.ne=>nil[7777]进行这个查询:MONGODB hm2_development['transactions'].find{:type=>{$ne=>nil}我知道,这个查询很奇怪,我已经重写了它。这对我来说是完全出乎意料的行为。@Ildar:我不知道Mongoid是否支持where:a=>b,:c=>d样式的查询,我使用的是MongoMapper。最后我提到的散列问题可能是问题的真正根源。您可能需要手动构建:$and查询。但固定的是固定的:
{ :type => 'planned' }
{ :type => { :$ne => nil } }