在 MongoDB 中,可以使用聚合管道操作符 $addFields 和正则表达式来提取字符串中的内容并将其转换为 Document 进行解析。/n/n下面是一个使用 $addFields 和正则表达式的示例聚合查询:/n/njavascript/ndb.collection.aggregate([/n {/n $addFields: {/n parsedDocument: {/n $regexFind: {/n input: '$stringField',/n regex: /(/w+):(/w+)//n }/n }/n }/n },/n {/n $addFields: {/n parsedDocument: {/n $arrayToObject: {/n $map: {/n input: '$parsedDocument',/n as: 'item',/n in: {/n k: { $arrayElemAt: ['$$item', 1] },/n v: { $arrayElemAt: ['$$item', 2] }/n }/n }/n }/n }/n }/n }/n])/n/n/n上述聚合查询中,假设有一个名为 collection 的集合,其中包含一个名为 stringField 的字段,值为包含 key:value 格式的字符串。聚合查询的第一阶段使用 $regexFind 操作符和正则表达式 /(/w+):(/w+)/ 来提取字符串中的 key:value 对,并将结果存储在 parsedDocument 字段中。/n/n第二个阶段使用 $arrayToObject 操作符和 $map 操作符来将 parsedDocument 字段中的数组转换为 Document$map 操作符遍历 parsedDocument 数组中的每个元素,并使用 $arrayElemAt 操作符将每个元素的第一个和第二个值分别映射到 kv 字段中。最后,$arrayToObject 操作符将 kv 字段对应的值转换为 Document。/n/n请注意,上述示例仅适用于字符串中只包含一个 key:value 对的情况。如果字符串中包含多个 key:value 对,你可以根据需要进行修改。


原文地址: https://www.cveoy.top/t/topic/p4kS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录