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]}
]
One option is to do the calculation using $map
with $range
and $log
operations:
db.collection.aggregate([
{$set: {
binary: {$reverseArray: {
$map: {
input: {$concatArrays: [
[0],
{$range: [1, {$ceil: {$log: ["$integerInput", 2]}}]}
]},
in: {$mod: [
{$floor: {$divide: [
"$integerInput",
{$pow: [2, "$$this"]}
]}},
2
]}
}
}}
}}
])
See How it works on the mongoDB playground
2