We can use simple $regex to find out documents with specific field have exact word in string value
For Example
Let's say we have following documents in collection sampledata
{
_id : ObjectId("583bbccc592818101fb7f3f8"),
"textdata" : "This is sample text data",
},
{
_id : ObjectId("583bbccc592818101fb7e43w"),
"textdata" : "data use by default",
},
{
_id : ObjectId("583bbccc592818101fb723ed"),
"textdata" : "bird can fly, This is not always true",
}
1 - Now we want only document which have "textdata" contains word "data"
db.sampledata.find({ "textdata" : { $regex : /\bdata\b/ })
Above query will return following documents
{
_id : ObjectId("583bbccc592818101fb7f3f8"),
"textdata" : "This is sample text data",
},
{
_id : ObjectId("583bbccc592818101fb7e43w"),
"textdata" : "data use by default",
}
2 - Now want only document which have "textdata" contains word "use"
db.sampledata.find({ "textdata" : { $regex : /\buse\b/ })
Above query will return following documents
{
_id : ObjectId("583bbccc592818101fb7e43w"),
"textdata" : "data use by default",
}
This will be helpful when your string data contains lots of words and you don't want to create $text index to minimize ram usages. For better performance use this trick with some index fields in where clause to narrow down document examine count.
To implement full text search in MongoDB use $text, You can search documents by word using $text when fields have text index (MongoDB official document on that)
For Example
Let's say we have following documents in collection sampledata
{
_id : ObjectId("583bbccc592818101fb7f3f8"),
"textdata" : "This is sample text data",
},
{
_id : ObjectId("583bbccc592818101fb7e43w"),
"textdata" : "data use by default",
},
{
_id : ObjectId("583bbccc592818101fb723ed"),
"textdata" : "bird can fly, This is not always true",
}
1 - Now we want only document which have "textdata" contains word "data"
db.sampledata.find({ "textdata" : { $regex : /\bdata\b/ })
Above query will return following documents
{
_id : ObjectId("583bbccc592818101fb7f3f8"),
"textdata" : "This is sample text data",
},
{
_id : ObjectId("583bbccc592818101fb7e43w"),
"textdata" : "data use by default",
}
2 - Now want only document which have "textdata" contains word "use"
db.sampledata.find({ "textdata" : { $regex : /\buse\b/ })
Above query will return following documents
{
_id : ObjectId("583bbccc592818101fb7e43w"),
"textdata" : "data use by default",
}
This will be helpful when your string data contains lots of words and you don't want to create $text index to minimize ram usages. For better performance use this trick with some index fields in where clause to narrow down document examine count.
To implement full text search in MongoDB use $text, You can search documents by word using $text when fields have text index (MongoDB official document on that)