skip to Main Content

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


  1. Chosen as BEST ANSWER

    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. Binary functions in Aggregation Framework are very limited. Performance wise this one should be better:

    db.collection.aggregate([
       {
          $set: {
             binary: {
                $function: {
                   body: function (val) {
                      return val.toString(2).split('').map(x => parseInt(x));
                   },
                   args: ["$integerInput"],
                   lang: "js"
                }
             }
          }
       }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search