How to find the keyword from the title in mongoDB?

Issue

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"})

Solution

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

Answered By – J.F.

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.