英文:
How to find the keyword from the title in mongoDB?
问题
如何在MongoDB中从标题中找到关键字?
从标题中找到包含一个或多个单词的关键字。
// 数据
{
title: "hello my name is joy",
section_name: "talk",
category_path: "info"
}
// 从关键字集合中
[
{keyword: "hello", section_name: "talk", category_path: "info", username: ["joy", "sadness"]},
{keyword: "hello joy", section_name: "talk", category_path: "info", username: ["joy"]},
{keyword: "shoes", section_name: "market", category_path: "sell", username: ["joy"]}
]
这是我想要获取的数据。
// 结果
[
{keyword: "hello", section_name: "talk", category_path: "info", username: ["joy", "sadness"]},
{keyword: "name joy", section_name: "talk", category_path: "info", username: ["joy"]}
]
我尝试了这段代码
// 没有数据
db.getCollection('keyword').find({"keyword": {$regex: "hello my name is joy"}, "section_name":"talk", "category_path": "info"})
英文:
How to find the keyword from the title in mongoDB?
Find the keyword from title included one or more words.
// data
{
title: "hello my name is joy", section_name: "talk", category_path: "info"
}
//From Keyword collection
[
{keyword: "hello", section_name: "talk", category_path: "info", username: ["joy", "sadness"]},
{keyword: "hello joy", section_name: "talk", category_path: "info", username: ["joy"]},
{keyword: "shoes", section_name: "market", category_path: "sell", username: ["joy"]}
]
This is the i want go to get the data.
// the Result
[
{keyword: "hello", section_name: "talk", category_path: "info", username: ["joy", "sadness"]},
{keyword: "name joy", section_name: "talk", category_path: "info", username: ["joy"]}
]
I tried this code
// No Data
db.getCollection('keyword').find({"keyword": {$regex: "hello my name is joy"}, "section_name":"talk", "category_path": "info"})
答案1
得分: 0
如果我理解正确,你可以尝试这样做。
我对Go不是很了解,所以可能还有其他更优雅的方法,但是思路是将字符串中的空格替换为|
,这样正则表达式就可以搜索每个单词。
regex := strings.Replace("hello my name is joy", " ", "|", -1)
然后你可以使用变量regex
构建你的查询,将其作为$regex
的值。
示例在这里。
英文:
If I've understood correctly you can try this.
I'm not an expert on Go so maybe there is another way more elegant, but the idea is to replace the spaces in the string with |
which means the regex will search for each word.
regex := strings.Replace("hello my name is joy", " ", "|", -1)
And then you can construct your query using the variable regex
as $regex
value.
Example here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论