如何在MongoDB中从标题中找到关键字?

huangapple go评论81阅读模式
英文:

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

huangapple
  • 本文由 发表于 2022年1月25日 22:43:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/70850646.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定