使用正则表达式从 MongoDB 中提取子字符串列表

编程入门 行业动态 更新时间:2024-10-27 08:25:22
本文介绍了使用正则表达式从 MongoDB 中提取子字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要提取与正则表达式匹配的字符串的一部分并将其返回.

I need to extract a part of a string that matches a regex and return it.

我有一组文件,例如:

{"_id" :12121, "fileName" : "apple.doc"}, {"_id" :12125, "fileName" : "rap.txt"}, {"_id" :12126, "fileName" : "tap.pdf"}, {"_id" :12126, "fileName" : "cricket.txt"},

我需要提取所有文件扩展名并返回{".doc", ".txt", ".pdf"}.

I need to extract all file extensions and return {".doc", ".txt", ".pdf"}.

我正在尝试使用 $regex 运算符来查找子字符串并汇总结果,但无法提取所需的部分并将其传递到管道中.

I am trying to use the $regex operator to find the sub strings and aggregate on the results but am unable to extract the required part and pass it down the pipeline.

我尝试过这样的事情但没有成功:

I have tried something like this without success:

aggregate([ { $match: { "name": { $regex: '/.[0-9a-z]+$/i', "$options": "i" } } }, { $group: { _id: null, tot: { $push: "$name" } } } ])

推荐答案

使用聚合框架和 $indexOfCP 运算符.在此之前,您最好的选择是 MapReduce.

It will be possible to do this in the upcoming version of MongoDB(as the time of this writing) using the aggregation framework and the $indexOfCP operator. Until then, your best bet here is MapReduce.

var mapper = function() { emit(this._id, this.fileName.substring(this.fileName.indexOf("."))) }; db.coll.mapReduce(mapper, function(key, value) {}, { "out": { "inline": 1 }} )["results"]

产量:

[ { "_id" : 12121, "value" : ".doc" }, { "_id" : 12125, "value" : ".txt" }, { "_id" : 12126, "value" : ".pdf" }, { "_id" : 12127, "value" : ".txt" } ]

为了完整起见,这里是使用聚合框架的解决方案*

db.coll.aggregate( [ { "$match": { "name": /.[0-9a-z]+$/i } }, { "$group": { "_id": null, "extension": { "$push": { "$substr": [ "$fileName", { "$indexOfCP": [ "$fileName", "." ] }, -1 ] } } }} ])

产生:

{ "_id" : null, "extensions" : [ ".doc", ".txt", ".pdf", ".txt" ] }

*MongoDB 的当前开发版本(撰写本文时).

更多推荐

使用正则表达式从 MongoDB 中提取子字符串列表

本文发布于:2023-11-05 09:04:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560428.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   列表   正则表达式   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!