u16suzuの blog

日々学んだことのメモブログです。

mongoid の any_of と or の違い

any_of は、前の条件をそのまま残して、その後に or 条件で挿入してくれる。 or は、前の条件も全部ひっくるめた or 条件を生成する。

コード例

実験したバージョン

[57] pry(main)> Mongoid::VERSION
=> "7.3.5"
> User.where(age: 33).any_of({name: "hoge"}, {tel: "123"}).selector
=> {"age"=>33, "$or"=>[{"n"=>"hoge"}, {"t"=>"123"}]}

> User.where(age: 33).or({name: "hoge"}, {tel: "123"}).selector
=> {"$or"=>[{"age"=>33}, {"n"=>"hoge"}, {"t"=>"123"}]}

ドキュメントより

  • any_of

    Adds a disjunction of the arguments as an additional constraint to the criteria already existing in the receiver.

レシーバにすでに存在する criteria に、追加の制約 として引数の論理和を追加します。

  • or

    Creates a disjunction using $or from the existing criteria in the receiver and the provided arguments. This behavior (receiver becoming one of the disjunction operands) matches ActiveRecord's or behavior. Use any_of to add a disjunction of the arguments as an additional constraint to the criteria already existing in the receiver.

$or を使用して、レシーバ側の既存の criteria と指定された引数から論理和を作成します。 この動作 (レシーバーが論理和オペランドの 1 つになる) は、ActiveRecord の or の挙動と一致します。 レシーバ側にすでに存在する条件に対する追加の制約として引数の論理和を追加したい場合は any_of を使います。