{"record":{"id":"aebd8b3fe9bfcdad","repo":"mongodb/mongoid","slug":"expression-must-be-a-hash-errors-invalidquery","errorCode":null,"errorMessage":"Expression must be a Hash: #{Errors::InvalidQuery.truncate_expr(criterion)}","messagePattern":"Expression must be a Hash: #(.+?)","errorType":"exception","errorClass":"Mongoid::Errors::InvalidQuery","httpStatus":null,"severity":"error","filePath":"lib/mongoid/criteria/queryable/selectable.rb","lineNumber":813,"sourceCode":"        #\n        # @example Create the selection.\n        #   selectable.expr_query(age: 50)\n        #\n        # @param [ Hash ] criterion The field/value pairs.\n        #\n        # @return [ Selectable ] The cloned selectable.\n        # @api private\n        # Operators permitted in a query expression without opt-in.\n        # Excludes $where (JS execution) and other operators not needed for\n        # ordinary application queries.\n        ALLOWED_QUERY_OPERATORS = %w[\n          $and $or $nor $not $text $comment $expr $jsonSchema $alwaysFalse $alwaysTrue\n        ].freeze\n\n        def expr_query(criterion)\n          raise ArgumentError, 'Criterion cannot be nil here' if criterion.nil?\n          unless criterion.is_a?(Hash)\n            raise Errors::InvalidQuery, \"Expression must be a Hash: #{Errors::InvalidQuery.truncate_expr(criterion)}\"\n          end\n\n          normalized = _mongoid_expand_keys(criterion)\n          clone.tap do |query|\n            normalized.each do |field, value|\n              field_s = field.to_s\n              if field_s.start_with?('$')\n                unless Mongoid.allow_unsafe_query_operators? || ALLOWED_QUERY_OPERATORS.include?(field_s)\n                  raise Errors::InvalidQuery,\n                        \"Operator '#{field_s}' is not allowed in a query expression. \" \\\n                        'Set Mongoid.allow_unsafe_query_operators = true to permit all operators.'\n                end\n                query.add_operator_expression(field_s, value)\n              else\n                query.add_field_expression(field, value)\n              end\n            end\n            query.reset_strategies!","sourceCodeStart":795,"sourceCodeEnd":831,"githubUrl":"https://github.com/mongodb/mongoid/blob/0da0e23d71adfbad31128c18e5e2c8c301c6f7c4/lib/mongoid/criteria/queryable/selectable.rb#L795-L831","documentation":"Error \"Expression must be a Hash: #{Errors::InvalidQuery.truncate_expr(criterion)}\" thrown in mongodb/mongoid.","triggerScenarios":"Thrown at lib/mongoid/criteria/queryable/selectable.rb:813 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":[],"exampleFix":null,"handlingStrategy":null,"validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"0da0e23d71adfbad31128c18e5e2c8c301c6f7c4","analyzedAt":"2026-08-23T06:25:47.656Z","schemaVersion":2},"datasetVersion":"2026-08-23T08:06:27.607Z"}