Mongo通过正则表达式查找:仅返回匹配的字符串 [英] Mongo find by regex: return only matching string
问题描述
我的应用程序具有以下堆栈:
My application has the following stack:
在Ruby上的Sinatra-> MongoMapper-> MongoDB
Sinatra on Ruby -> MongoMapper -> MongoDB
应用程序将几个条目放入数据库中.为了交叉链接到其他页面,我添加了某种语法.例如:
The application puts several entries in the database. In order to crosslink to other pages, I've added some sort of syntax. e.g.:
咖啡是一种黑色的含咖啡因的液体,由豆类制成. {茶}是用树叶制成的.两种饮料有时都可以与{milk}一起享用
Coffee is a black, caffeinated liquid made from beans. {Tea} is made from leaves. Both drinks are sometimes enjoyed with {milk}
在此示例中,{Tea}将链接到另一个有关tea的数据库条目.
In this example {Tea} will link to another DB entry about tea.
我试图查询我的mongoDB有关所有链接术语"的信息.通常在红宝石中,我会做这样的事情:/{([a-zA-Z0-9])+}/
其中,()
将返回匹配的字符串.但是在mongo中,我得到了整个记录.
I'm trying to query my mongoDB about all 'linked terms'. Usually in ruby I would do something like this: /{([a-zA-Z0-9])+}/
where the ()
will return a matched string. In mongo however I get the whole record.
我如何才能得到mongo仅将我要查找的记录中匹配的部分退还给我.因此,对于上面的示例,它将返回:
How can I get mongo to return me only the matched parts of the record I'm looking for. So for the example above it would return:
["Tea", "milk"]
我试图避免将整个记录拉入Ruby并在那里进行处理
I'm trying to avoid pulling the entire record into Ruby and processing them there
推荐答案
我不知道我是否理解.
db.yourColl.aggregate([
{
$match:{"yourKey":{$regex:'[a-zA-Z0-9]', "$options" : "i"}}
},
{
$group:{
_id:null,
tot:{$push:"$yourKey"}
}
}])
如果您不想在tot
中重复,请使用$addToSet
If you don't want to have duplicate in tot
use $addToSet
这篇关于Mongo通过正则表达式查找:仅返回匹配的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!