MongoDB 聚合查询字符串解析为数组或文档 - 详细示例
在MongoDB中,可以使用聚合查询的$project和$split操作符将字符串转换为数组或文档进行解析。\n\n以下是将字符串解析为数组的示例:\n\njava\ndb.collection.aggregate([\n {\n \$project: {\n stringArray: { \$split: ["\$stringField", ", "] }\n }\n }\n])\n\n\n在上面的示例中,$split操作符将$stringField字段的值按逗号和空格分割为一个字符串数组。结果将作为stringArray字段返回。\n\n以下是将字符串解析为文档的示例:\n\njava\ndb.collection.aggregate([\n {\n \$project: {\n parsedDocument: {\n \$arrayToObject: {\n \$map: {\n input: { \$split: ["\$stringField", ", "] },\n in: {\n k: { \$arrayElemAt: [{ \$split: ["\$\$this", ":" ] }, 0] },\n v: { \$arrayElemAt: [{ \$split: ["\$\$this", ":" ] }, 1] }\n }\n }\n }\n }\n }\n }\n])\n\n\n在上面的示例中,$split操作符将$stringField字段的值按逗号和空格分割为一个字符串数组。然后,使用$map操作符将每个数组元素拆分为键值对。最后,使用$arrayToObject操作符将键值对数组转换为一个文档。结果将作为parsedDocument字段返回。\n\n这些示例中的操作符是MongoDB的聚合管道操作符,可以在聚合查询中使用。请根据实际情况调整操作符的参数和使用方式。
原文地址: https://www.cveoy.top/t/topic/p4py 著作权归作者所有。请勿转载和采集!