Im new to Mongo and would like some help on how to do a phrase search on Atlas Mongo. I have tried doing a title search from the out of the box movies collection using the "sample-mflix" database.
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);
}
}
Using the exact phrase works for title (eg "A Year Along the Abandoned Road"), but say if I wish to search for "A year". How can I return the same result(s) that just shows "A Year" in the title?
I tried query = {$text:{$search:""A Year ""}}, but this returned many results that were incorrect. I have checked the indexes on Atlas and it seems this is already indexed : (cast_text_fullplot_text_genres_text_title_text). I used https://www.geeksforgeeks.org/search-text-in-mongodb/ as a reference but this didnt seem work in my case.
You have an extra space in your $search
criteria.
I think what you meant was:
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.'
*/
However you mentioned that:
but say if I wish to search for "A year". How can I return the same result(s) that just shows "A Year" in the title?
Then you will need to pass in the $caseSensitive
option and set it to false
so that it searches for uppercase and lowercase (case ignored):
const query = {$text:{$search:"\"A Year\"", $caseSensitive: false}};
/* Returns:
'A Year'
'a Year.'
'a year ago.'
'A year to remember.'
*/