MongoDB查询$ in与元素的正则表达式数组 [英] MongoDB query $in with regex array of element

查看:418
本文介绍了MongoDB查询$ in与元素的正则表达式数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我正在尝试实现一个查询,该查询正在尝试对一堆文档执行正则表达式搜索(其中包含数组列表)

Ok i am trying to implement a query, which is trying to perform regex search ( which contains an array list ) on a bunch of document

我很难解释...所以我基本上是直接说到这一点.

Its hard for me to explain...so I am basically coming to direct point.

存在与正则表达式数组一起使用的查询...

There is query which works with regex array...

db.paper.find({"category": {$in: [ /xd/, /sd/, /ad/ ] }})

有些查询不适用于正则表达式数组...

There is query which doesn't works with regex array...

db.paper.find({"category": {$in: [ "/xd/", "/sd/", "/ad/" ] }})

所以基本上我想要从字符串数组中删除"符号...以便我可以在下面的查询中执行..

So basically what I want is remove "" sign from string array...so that i can perform below query..

var sea = [ "/xd/", "/sd/", "/ad/" ];
db.paper.find({"category": {$in: sea }});

推荐答案

当双引号出现时,它不起作用,因为它们被解释为字符串而不是RegExp对象.因此,要使其正常工作,必须首先使用Javascript将其转换为RegExp对象.

it does not work when the double quotes are present because they are interpreted as strings instead of as RegExp objects. So to make it to work, you have to convert it to RegExp objects first in Javascript like this.

var sea = [ "xd", "sd", "ad" ]; // Note: no slashes
var regex = [];
for (var i = 0; i < sea.length; i++) {
    regex[i] = new RegExp(sea[i]);
}
db.paper.find({"category": {$in: regex}});

请记住,MongoDB shell使用Javascript

Remember, MongoDB shell uses Javascript

这篇关于MongoDB查询$ in与元素的正则表达式数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆