mongodb/mongoid · error · Mongoid::Errors::InvalidQuery

Operator '#{field_s}' is not allowed in a query expression.

Error message

Operator '#{field_s}' is not allowed in a query expression. Set Mongoid.allow_unsafe_query_operators = true to permit all operators.

What it means

Error "Operator '#{field_s}' is not allowed in a query expression. Set Mongoid.allow_unsafe_query_operators = true to permit all operators." thrown in mongodb/mongoid.

Source

Thrown at lib/mongoid/criteria/queryable/selectable.rb:822

        # Excludes $where (JS execution) and other operators not needed for
        # ordinary application queries.
        ALLOWED_QUERY_OPERATORS = %w[
          $and $or $nor $not $text $comment $expr $jsonSchema $alwaysFalse $alwaysTrue
        ].freeze

        def expr_query(criterion)
          raise ArgumentError, 'Criterion cannot be nil here' if criterion.nil?
          unless criterion.is_a?(Hash)
            raise Errors::InvalidQuery, "Expression must be a Hash: #{Errors::InvalidQuery.truncate_expr(criterion)}"
          end

          normalized = _mongoid_expand_keys(criterion)
          clone.tap do |query|
            normalized.each do |field, value|
              field_s = field.to_s
              if field_s.start_with?('$')
                unless Mongoid.allow_unsafe_query_operators? || ALLOWED_QUERY_OPERATORS.include?(field_s)
                  raise Errors::InvalidQuery,
                        "Operator '#{field_s}' is not allowed in a query expression. " \
                        'Set Mongoid.allow_unsafe_query_operators = true to permit all operators.'
                end
                query.add_operator_expression(field_s, value)
              else
                query.add_field_expression(field, value)
              end
            end
            query.reset_strategies!
          end
        end

        # Create a javascript selection.
        #
        # @api private
        #
        # @example Create the javascript selection.
        #   selectable.js_query("this.age == 50")

View on GitHub (pinned to 0da0e23d71)

When it happens

Trigger: Thrown at lib/mongoid/criteria/queryable/selectable.rb:822 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of mongodb/mongoid@0da0e23d71 (2026-08-23). Data as JSON: /api/errors/a1bf96cf5a92472b. Report an issue: GitHub.