Home > Enterprise >  MongoDB: How to only pull document with exact search term
MongoDB: How to only pull document with exact search term

Time:06-06

I'm sure this is somewhere on here but I can't seem to find it. I'm trying to pull a document from a large file that only matches an exact term in a field, as opposed to anything with those letters in it.

More precisely, I'm trying to use .find({"name":"Eli"}) to pull the documents with that name, but my search is pulling every name with those letters (such as elizabeth or ophelia)

CodePudding user response:

You can use a regular expression match to make sure you do not return names that share the same character formation.

Something like this:

const name = "Eli"
const query = new RegExp(`^${name}$`)
const user = await Collection.find({ name: { $regex: query } })

I am using 2 key operators from RegEx here: ^ and $

Putting ^ in front of a regular expression will match all strings that start with the pattern given.

Putting $ at the end of a regular expression will match all strings that end with the pattern given.

So essentially you are asking mongoose to find the record where the name both begins and ends with Eli. This will prevent Elizabeth from showing up in your result, but won't filter out other Eli's.

  • Related