You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB 6.0及更早版本聚合管道中正整数转二进制数组方法

MongoDB 6.0及更早版本聚合管道将正整数转为二进制数组的方案

针对MongoDB 6.0及更早版本聚合管道不支持$bit操作的限制,可通过数学计算与数组操作组合实现正整数到二进制数组的转换,以下是具体实现方案:

完整聚合管道代码

db.collection.aggregate([
  {
    $addFields: {
      bitLength: {
        $add: [
          { $floor: { $log2: "$integerInput" } },
          1
        ]
      }
    }
  },
  {
    $addFields: {
      indices: { $range: [0, "$bitLength"] }
    }
  },
  {
    $addFields: {
      binary: {
        $map: {
          input: "$indices",
          as: "i",
          in: {
            $let: {
              vars: {
                weight: { $pow: [2, { $subtract: [{ $subtract: ["$bitLength", 1] }, "$$i"] }] }
              },
              in: {
                $cond: [
                  { $gte: ["$integerInput", "$$weight"] },
                  1,
                  0
                ]
              }
            }
          }
        }
      }
    }
  },
  {
    $project: { bitLength: 0, indices: 0 }
  }
])

各阶段说明

  1. 计算二进制位数:
    通过$log2计算整数的对数,取整后加1得到该整数二进制的有效位数。例如13的对数约为3.7,取整后加1得到4位。
  2. 生成索引数组:
    用$range生成从0到位数-1的索引数组,用于遍历二进制的每一位。
  3. 生成二进制数组:
    借助$map遍历索引数组,对每个索引计算对应位的权重(2的幂次),判断原整数是否大于等于该权重,是则标记为1,否则为0,最终得到高位在前的二进制数组。
  4. 清理临时字段:
    通过$project移除过程中生成的bitLength和indices临时字段,保留目标输出结构。

测试验证

将示例输入数据传入上述聚合管道,将得到期望的输出结果:

[
  {_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]}
]

内容的提问来源于stack exchange,提问作者nimrod serok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 00:55:12