[英]Find all occurrences of elements in an array in a string
I have documents akin to the following format: 我的文件类似于以下格式:
When a user performs a search, they send an array to the backend. 用户执行搜索时,他们将数组发送到后端。 This array contains at least one element.
此数组包含至少一个元素。
Say that they send ['javascript']
to the backend. 假设他们将
['javascript']
发送到后端。 Is there a way to query MongoDB to find out with documents contain the word javascript
? 有没有一种查询MongoDB的方法来查找包含
javascript
单词的文档?
I tried something like, 我尝试过类似
db.find({ body: { $all:['javascript'] } });
but that only works if body
is an array as well. 但这仅在
body
也是数组的情况下才有效。 Any way to accomplish this? 有什么办法可以做到这一点?
you could use a pipe-delimited regex pattern with the keywords list like this: 您可以将管道分隔的正则表达式模式与关键字列表一起使用,如下所示:
const subStrings = ["javascript", "php", "python"];
const regex = subStrings.join("|");
db.find ({
body: { $regex: regex, $options: 'i' }
});
Use the $regex
operator and pass it a regex contained in a string: 使用
$regex
运算符,并将字符串中包含的正则表达式传递给它:
db.find({ body: { $regex: ".*javascript.*" }});
You could also do this: 您也可以这样做:
db.find({ body: /.*javascript.*/ });
db.find({ body: /javascript/ });
First, you need to create a text index on the fields you want to search on. 首先,您需要在要搜索的字段上创建文本索引。 If you want to search on all fields
如果要搜索所有字段
db.collection.createIndex( { "$**": "text" } )
Or if you want to include only few specific fields, than 或者,如果您只想包含几个特定字段,则可以
db.collection.createIndex( { title: "text", body: "text" } )
You can add weightage also, for eg. 您也可以添加重量,例如。 in your case title should be having more weightage than description.
在您的情况下,标题的权重应大于说明。
Then you can have a search like: 然后,您可以进行如下搜索:
db.collection.find( { $text: { $search: "java javascript python" } } )
this will search for all documents which contains any or all these words. 这将搜索包含任何或所有这些单词的所有文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.