简体   繁体   中英

How to find fields that contains one of array elements?

It's easy for find fields that contain an string like this:

db.users.findOne({"username" : {$regex : ".*son.*"}});

I want to know if there is a way to check all array elements this way? for example something like this:

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

You can use the native OR ( | ) condition of Regex.

Example:

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

You can try this one. First you can make regex array for s then can use that new array with $in operator. like bellow

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM