如何在 mongoDB 聚合中将正整数转换为二进制

问题描述 投票:0回答:1

我正在寻找一种将正整数转换为 mongoDB 聚合管道内的二进制数组的方法。

$bit
操作不能在聚合管道内使用。

这个问题是关于 mongoDB 版本 6.0 及更早版本

输入示例数据:

[
  {_id: 1, integerInput: 13},
  {_id: 2, integerInput: 3 },
  {_id: 3, integerInput: 1 },
  {_id: 4, integerInput: 17},
  {_id: 5, integerInput: 10}
]

要求的输出:

[
  {_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]}
]
mongodb mongodb-query aggregation-framework
1个回答
0
投票

一种选择是使用

$map
以及
$range
$log
运算进行计算:

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
            ]}
          }
      }}
  }}
])

查看它在 mongoDB Playground 上的工作原理

© www.soinside.com 2019 - 2024. All rights reserved.