I was looking for a way to convert a positive integer into a binary array inside a mongoDB aggregation pipeline.
There is $bit
operation which can’t be used inside an aggregation pipeline.
This question is regarding mongoDB version 6.0 and older
Input example data:
[
{_id: 1, integerInput: 13},
{_id: 2, integerInput: 3 },
{_id: 3, integerInput: 1 },
{_id: 4, integerInput: 17},
{_id: 5, integerInput: 10}
]
Requested output:
[
{_id: 1, integerInput: 13, binary: [1, 1, 0, 1]},
{_id: 2, integerInput: 3 , binary: [1, 1]},
{_id: 3, integerInput: 1 , binary: [1]},
{_id: 4, integerInput: 17, binary: [1, 0, 0, 0, 1]},
{_id: 5, integerInput: 10, binary: [1, 0, 1, 0]}
]
2
Answers
One option is to do the calculation using
$map
with$range
and$log
operations:See How it works on the mongoDB playground
Binary functions in Aggregation Framework are very limited. Performance wise this one should be better: