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
相关产品推荐
相关产品推荐

