Atlas Mongo DB - 子短语标题搜索

问题描述 投票:0回答:1

我是 Mongo 新手,希望获得有关如何在 Atlas Mongo 上进行短语搜索的帮助。我尝试使用“sample-mflix”数据库从开箱即用的电影集合中进行标题搜索。

export default async (req, res) => {
    
  try {
    const client = await clientPromise;
    const db = client.db("sample_mflix");

    //const query = { title: "A Year Along the Abandoned Road"} // this works

    const query =  {$text:{$search:"\"A Year \""}} // this produces unexpected results

    const options = {
      // sort returned documents in ascending order by title (A->Z)
      sort: { title: 1 },
      // Include only the `title` and `imdb` fields in each returned document
      projection: { _id: 0, title: 1, imdb: 1 },
    };


    const movies = await db
        .collection("movies")
        .find(query, options)
         //.sort({ metacritic: -1 })
         //.limit(100)
        .toArray();

    res.json(movies);
} catch (e) {
    console.error(e);
}
}

使用确切的短语作为标题(例如“沿着废弃道路的一年”),但请说明我是否想搜索“一年”。如何返回标题中仅显示“一年”的相同结果?

我尝试了 query = {$text:{$search:""A Year ""}},但这返回了许多不正确的结果。我已经检查了 Atlas 上的索引,似乎已经索引了:(cast_text_fullplot_text_genres_text_title_text)。我使用 https://www.geeksforgeeks.org/search-text-in-mongodb/ 作为参考,但这对我来说似乎不起作用。

mongodb search title atlas phrase
1个回答
0
投票

您的

$search
标准中有一个额外的空间。

我认为你的意思是:

const query =  {$text:{$search:"\"A Year\""}} //< Note the \ straight after the word Year (no spaces after)
/* Returns:
'A Year'
'A Year.'
'A Year ago.'
'A Year to remember.' 
*/

但是你提到:

但请说明我是否想搜索“一年”。如何返回标题中仅显示“一年”的相同结果?

然后您需要传入

$caseSensitive
选项并将其设置为
false
,以便它搜索大写和小写(忽略大小写):

const query =  {$text:{$search:"\"A Year\"", $caseSensitive: false}};

/* Returns:
'A Year'
'a Year.'
'a year ago.'
'A year to remember.' 
*/
© www.soinside.com 2019 - 2024. All rights reserved.