Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-4861

Useless $and when calling Foo.and(Foo.or(...))

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 7.1.1
    • Affects Version/s: 7.1.0
    • Component/s: Query
    • None

      In https://jira.mongodb.org/browse/MONGOID-4860 the following query on an association was proposed:

      class User
        include Mongoid::Document
        has_many :comments
      end
      
      class Comment
        include Mongoid::Document
        belongs_to :user, optional: true
        field :time, type: Integer
      end
      
      user = User.create!
      user.comments.and(Comment.or({:time.gt => 5}, {:time => nil})).selector
      
      => {"user_id"=>BSON::ObjectId('5e7498a4e1b8323c9851dba6'), "$and"=>[{"$or"=>[{"time"=>{"$gt"=>5}}, {"time"=>nil}]}]}
      

      This query generates an unneeded $and over the $or.

      It appears that this behavior applies outside of associations also:

      irb(main):014:0> Comment.where(foo: 1).and(Comment.or({:time.gt => 5}, {:time => nil})).selector 
      => {"foo"=>1, "$and"=>[{"$or"=>[{"time"=>{"$gt"=>5}}, {"time"=>nil}]}]}
      irb(main):015:0> Comment.and(Comment.or({:time.gt => 5}, {:time => nil})).selector=> {"$and"=>[{"$or"=>[{"time"=>{"$gt"=>5}}, {"time"=>nil}]}]}
      

      https://jira.mongodb.org/browse/MONGOID-4870 adds a few tests that also have redundant $ands in them that should be considered for removal as part of this ticket.

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: