mongodb/mongoid · error · Mongoid::Errors::InvalidQuery
$size argument must be a non-negative integer: #
Error message
$size argument must be a non-negative integer: #{Errors::InvalidQuery.truncate_expr(condition)} What it means
Raised by the in-memory $size matcher when the condition is not a non-negative integer (or convertible whole number). $size matches exact array length, so fractional or negative operands are meaningless and rejected.
Solutions
- Pass a non-negative Integer to $size, e.g. { tags: { '$size' => 3 } }
- Use $expr with $isArray/$size for more complex length comparisons
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at lib/mongoid/matcher/size.rb:22 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/54fc9e6692e76a29.
Report an issue: GitHub.
Appendix: source
Thrown at lib/mongoid/matcher/size.rb:22
#
# @see https://www.mongodb.com/docs/manual/reference/operator/query/size/
#
# @api private
module Size
# Returns whether a value satisfies a $size expression.
#
# @param [ true | false ] exists Not used.
# @param [ Numeric ] value The value to check.
# @param [ Integer | Array<Object> ] condition The $size condition
# predicate, either a non-negative Integer or an Array to match size.
#
# @return [ true | false ] Whether the value matches.
#
# @api private
module_function def matches?(_exists, value, condition)
case condition
when Float
raise Errors::InvalidQuery, "$size argument must be a non-negative integer: #{Errors::InvalidQuery.truncate_expr(condition)}"
when Numeric
if condition < 0
raise Errors::InvalidQuery, "$size argument must be a non-negative integer: #{Errors::InvalidQuery.truncate_expr(condition)}"
end
else
raise Errors::InvalidQuery, "$size argument must be a non-negative integer: #{Errors::InvalidQuery.truncate_expr(condition)}"
end
if value.is_a?(Array)
value.length == condition
else
false
end
end
end
end
end
View on GitHub (pinned to 0da0e23d71)