Skip to content

BitwiseOperatorBuilder should have int overloads to avoid implicit type conversion #5146

@victorljii

Description

@victorljii

Summary

The BitwiseOperatorBuilder class in Update.java currently only provides long parameter versions for the and(), or(), and xor() methods. When passing an int value, Java's implicit type conversion promotes it to long, which results in the MongoDB document storing the value as a 64-bit integer (NumberLong) instead of a 32-bit integer (NumberInt).

Current Behavior

Update update = new Update().bitwise("field").or(16); 
// Results in: { "$bit": { "field": { "or": NumberLong(16) } } }

Even though 16 is an int, and field stored int value, it gets converted to long and stored as NumberLong in MongoDB. A simple example blow:
https://github.com/victorljii/spring-data-mongodb-lab

Proposed Solution

Add int overloads for all three bitwise methods:

		public Update and(int value) {

			addFieldOperation(BitwiseOperator.AND, value);
			return reference;
		}

		public Update or(int value) {

			addFieldOperation(BitwiseOperator.AND, value);
			return reference;
		}

		public Update xor(int value) {

			addFieldOperation(BitwiseOperator.AND, value);
			return reference;
		}

The underlying addFieldOperation method already accepts Number, so this change is straightforward and backward-compatible.

Why This Matters

  1. Type Preservation: MongoDB distinguishes between 32-bit and 64-bit integers. Applications that rely on specific integer types for schema consistency or interoperability with other systems may be affected.
  2. Consistency: Other methods in Update (e.g., inc(String key, Number inc)) already accept Number type, allowing type preservation.
  3. API Completeness: Providing both int and long overloads gives developers explicit control over the stored type.

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions