在MongoDB中使用find()查找多个单词 [英] Finding multiple words with find() in MongoDB

查看:584
本文介绍了在MongoDB中使用find()查找多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Python与MongoDB结合使用.我有一个单词数组,我用这些单词搜索Mongo数据库并使用$in将任何文档与匹配字段进行匹配,例如

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

上面的方法效果很好,但是我希望能够使用正则表达式.现在的问题是,如果数组中的单词之一被拼写为accus而不是accuse,我希望find()查询仍返回与单词accuse有关的文档(记录/行). /p>

我已经尝试过了,但这根本不起作用,没有结果返回.

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

数组中的每个元素在单词前均以^读取, 例如['^work', '^accus', '^planet']

我只是以错误的方式来做这件事吗?

解决方案

很抱歉,您的问题很晚才回答.您应该使用一个正则表达式,而不是它们的数组,例如:

'^[work|accus*|planet]'

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?

解决方案

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

'^[work|accus*|planet]'

这篇关于在MongoDB中使用find()查找多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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