Python 如何查找包含一个数组元素的字段?

Python 如何查找包含一个数组元素的字段?,python,mongodb,Python,Mongodb,查找包含以下字符串的字段很容易: db.users.findOne({"username" : {$regex : ".*son.*"}}); s = ['one', 'two', 'three'] db.users.findOne({"username" : {$regex : ".*s.*"}}); 我想知道是否有办法以这种方式检查所有数组元素? 例如,类似这样的事情: db.users.findOne({"username" : {$regex : ".*son.*"}}); s =

查找包含以下字符串的字段很容易:

db.users.findOne({"username" : {$regex : ".*son.*"}});
s = ['one', 'two', 'three']
db.users.findOne({"username" : {$regex : ".*s.*"}});
我想知道是否有办法以这种方式检查所有数组元素? 例如,类似这样的事情:

db.users.findOne({"username" : {$regex : ".*son.*"}});
s = ['one', 'two', 'three']
db.users.findOne({"username" : {$regex : ".*s.*"}});

您可以使用正则表达式的本机
)条件

例如:

s = ['one', 'two', 'three'];
db.users.findOne({"username" : {$regex: ".*(" + '|'.join(s) + ").*"}});

您可以使用正则表达式的本机
)条件

例如:

s = ['one', 'two', 'three'];
db.users.findOne({"username" : {$regex: ".*(" + '|'.join(s) + ").*"}});

你可以试试这个。首先,您可以为s生成
regex
数组,然后可以将该新数组与
$in
运算符一起使用。像吼叫

var s = ['one', 'two', 'three'];
s = s.map(function (elm) { return new RegExp(elm, "i"); });
db.users.findOne({username:{$in: s}})

你可以试试这个。首先,您可以为s生成
regex
数组,然后可以将该新数组与
$in
运算符一起使用。像吼叫

var s = ['one', 'two', 'three'];
s = s.map(function (elm) { return new RegExp(elm, "i"); });
db.users.findOne({username:{$in: s}})

它引发了一个错误:“list”对象没有属性“join”@ehsanshirzadi抱歉,我以为它是在JavaScript中的(不知怎么的,我错过了Python标记)。我更新了我的答案。@ehsanshirzadi最好的答案是这个。您需要的只是合并所有文本,以确定用户名字段是否包含。因此,按照建议,使用
运算符生成一个大的正则表达式字符串,并在
$regex
运算符中给出它。它会引发一个错误:“list”对象没有属性“join”@ehsanshirzadi抱歉,我以为它是在JavaScript中(不知何故,我错过了Python标记)。我更新了我的答案。@ehsanshirzadi最好的答案是这个。您需要的只是合并所有文本,以确定用户名字段是否包含。因此,根据建议,使用
运算符生成一个大的正则表达式字符串,并在
$regex
运算符中给出它。它不是JavaScript代码,而是python中的
map
,因此您可以在python中使用
map
@ehsanshirzadino它是JavaScript代码,但在python中也是
map
,因此您可以在python中使用
map
@埃桑什扎迪