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

MongoDB数组投影需求:将itemIds布尔键转为指定数组适配Azure认知搜索

MongoDB投影转换文档结构(适配Azure Cognitive Search迁移)

原始MongoDB文档结构:

{
   "itemIds":{
      "12341234-1234-1234-1234-123412341234": true,
      "23452345-2345-2354-2345-234523452354": false,
      "34563456-3456-3456-3456-345634563456": true
   }
}

需要转换为适配Azure Cognitive Search的目标格式:

{
   "itemIds": ["12341234-1234-1234-1234-123412341234",
               "34563456-3456-3456-3456-345634563456"]
}

直接用普通投影无法实现这个转换,得用MongoDB聚合管道来处理,具体查询语句如下:

db.collection.aggregate([
  {
    $project: {
      itemIds: { $objectToArray: "$itemIds" }
    }
  },
  {
    $project: {
      itemIds: {
        $map: {
          input: {
            $filter: {
              input: "$itemIds",
              cond: { $eq: ["$$this.v", true] }
            }
          },
          in: "$$this.k"
        }
      }
    }
  }
])

语句说明

  • 第一个$project阶段:通过$objectToArray把itemIds对象转成键值对数组,每个元素结构为{k: "ID字符串", v: 布尔值};
  • 第二个$project阶段:
    1. 用$filter筛掉数组中v为false的元素;
    2. 用$map把筛选后元素的k值(也就是目标ID)提取出来,组成最终的itemIds数组。

内容的提问来源于stack exchange,提问作者Kyle W

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:41:27