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
$searchcriteria.I think what you meant was:
However you mentioned that:
Then you will need to pass in the
$caseSensitiveoption and set it tofalseso that it searches for uppercase and lowercase (case ignored):