Finding multiple words with find() in MongoDB

2020-08-17 18:19发布

问题:

I'm using Python in conjunction with MongoDB. I have an array of words, and I use these words to search the Mongo database and match any documents with matching fields using $in, e.g.

collection.find({"word":{"$in":words}})

The above works very well, but I want to be able to use a regex. The problem is now that if one of the words in the array was spelt accus instead of accuse, I want the find() query to still return the document (record/row) relating to the word accuse.

I've tried this, which doens't work at all, no results are returned.

collection.find({"word":{"$in":{"$regex":words}}})

Each element in the array reads with ^ preceding the word, e.g. ['^work', '^accus', '^planet']

Am I just going about this the wrong way?

回答1:

Sorry for late answer, just googled your question. You should use one regex, not an array of them, like:

'^[work|accus*|planet]'


回答2:

You can't use $regex inside an $in expression, but you can use JS regex (the "/regex/" kind).

From the MongoDB docs at http://docs.mongodb.org/v2.2/reference/operator/query/regex/#in-expressions:

To include a regular expression in an $in query expression, you can only use JavaScript regular expression objects (i.e. /pattern/ ). You cannot use $regex operator expressions inside an $in.

BTW, I know it's a very late answer, but hopefully it'll serve the queriers of the future...



回答3:

According to Mongo docs the currect way to this is the folllowing

var words = [/hello/, /^world/];// array of regex
db.getCollection('word collection').find({"word" : {$in : words}});

To accomplish this in JS you can create an array of RegEXp Objects and pass that array as the value of $in some thing like this :

words = words.map(function(v){return new RegExp(v)});


回答4:

Using Spring Data API, one can do the query as the following:

Query query = new Query();
query.addCriteria(Criteria.where("words").in(Pattern.compile(regex-String)));
find(query)

This will find all the documents with an array field called words with element in that array that match the regex.