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

MongoDB中更新文档subject数组内指定格式元素的方法

MongoDB数组元素批量更新:移除特定路径片段

需求说明

需要更新MongoDB文档中subject数组内**以http://test开头且包含/base**的元素,将其替换为去除/base后的内容。例如把"http://test/timespan/base/1"修改为"http://test/timespan/1"。

原始文档示例

{
  "_id": {
    "$oid": "1233"
  },
  "type": "Entity",
  "subject": [
    "http://test/concept/114",
    "http://test/timespan/base/1",
    "http://wikidata/1233"
  ]
}

更新后预期结果

{
  "_id": {
    "$oid": "1233"
  },
  "type": "Entity",
  "subject": [
    "http://test/concept/114",
    "http://test/timespan/1",
    "http://wikidata/1233"
  ]
}

解决方案

使用MongoDB聚合管道结合$map、$cond和$replaceOne操作符,实现数组元素的批量条件更新:

db.collection.updateMany(
  {}, // 留空表示匹配所有文档,如需指定过滤条件可在此添加(如 { type: "Entity" })
  [
    {
      $set: {
        subject: {
          $map: {
            input: "$subject",
            as: "item",
            in: {
              $cond: {
                if: {
                  $and: [
                    { $regexMatch: { input: "$$item", regex: /^http:\/\/test/ } },
                    { $regexMatch: { input: "$$item", regex: /\/base/ } }
                  ]
                },
                then: { $replaceOne: { input: "$$item", find: "/base", replacement: "" } },
                else: "$$item"
              }
            }
          }
        }
      }
    }
  ]
)

代码说明

  • $map:遍历subject数组的每一个元素
  • $cond:判断元素是否同时满足两个正则匹配条件:以http://test开头、包含/base
  • $replaceOne:对符合条件的元素,移除第一个出现的/base片段;如果需要移除所有/base,可替换为$replaceAll操作符

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:30:53