Fuzzy search in MongoDB
Today, we will discuss fuzzy search and how to do it with MongoDB.
We will start by using $regex
the operator and $text
the query. In addition, we will learn to Fuse.js
perform fuzzy search on documents using a JavaScript library called .
What is fuzzy search
Using fuzzy search, we can search for text that does not match exactly but closely. This is useful to find relevant results even if the search term is misspelled.
For example, Google will show us various web pages related to our search term even if we type it wrong. Using regular expressions (also known as regex) is also a very beneficial and time-saving way to implement fuzzy search.
Create a sample collection in MongoDB
We will learn about fuzzy search from basic to advanced level. To practice it, let's create a collection_one
sample collection called which has one field for each document, ie name
.
_id
is created automatically; we don't have to create it. You can use the following query to perform the same operation.
Sample code:
> db.createCollection('collection_one')
> db.collection_one.insertMany([
{ name : 'Mehvish Ashiq'},
{ name : 'Jennifer Johnson'},
{ name : 'Natalie Robinson'},
{ name : 'John Ferguson'},
{ name : 'Samuel Patterson'},
{ name : 'Salvatore Callahan'},
{ name : 'Mikaela Christensen'}
])
> db.collection_one.find()
Output:
{ "_id" : ObjectId("62939a37b3a0d806d251ddae"), "name" : "Mehvish Ashiq" }
{ "_id" : ObjectId("62939a37b3a0d806d251ddaf"), "name" : "Jennifer Johnson" }
{ "_id" : ObjectId("62939a37b3a0d806d251ddb0"), "name" : "Natalie Robinson" }
{ "_id" : ObjectId("62939a37b3a0d806d251ddb1"), "name" : "John Ferguson" }
{ "_id" : ObjectId("62939a37b3a0d806d251ddb2"), "name" : "Samuel Patterson" }
{ "_id" : ObjectId("62939a37b3a0d806d251ddb3"), "name" : "Salvatore Callahan" }
{ "_id" : ObjectId("62939a37b3a0d806d251ddb4"), "name" : "Mikaela Christensen" }
$regex
Performing fuzzy search in MongoDB
using the operator
Sample code:
> db.collection_one.find({"name": /m/})
Output:
{ "_id" : ObjectId("62939a37b3a0d806d251ddb2"), "name" : "Samuel Patterson" }
In this code, we name
perform a fuzzy search on the field and retrieve all documents name
where the field contains the letters .m
As you can see, we have only one m
record containing the letter , but there are two more M
documents starting with (uppercase letter). To handle this, we can use i
a modifier like the following , which performs a case-insensitive search.
Sample code:
> db.collection_one.find({"name": /m/i})
Output:
{ "_id" : ObjectId("62939a37b3a0d806d251ddae"), "name" : "Mehvish Ashiq" }
{ "_id" : ObjectId("62939a37b3a0d806d251ddb2"), "name" : "Samuel Patterson" }
{ "_id" : ObjectId("62939a37b3a0d806d251ddb4"), "name" : "Mikaela Christensen" }
It shows that properly designed regular expressions are very important; otherwise, we may get misleading results. We can also do the same thing in the following way.
Sample code (case insensitive search):
> db.collection_one.find({'name': {'$regex': 'm','$options': 'i'}})
Output:
{ "_id" : ObjectId("62939a37b3a0d806d251ddae"), "name" : "Mehvish Ashiq" }
{ "_id" : ObjectId("62939a37b3a0d806d251ddb2"), "name" : "Samuel Patterson" }
{ "_id" : ObjectId("62939a37b3a0d806d251ddb4"), "name" : "Mikaela Christensen" }
Similarly, we can get all name
documents ending with a two-letter combination as on
.
Sample code:
> db.collection_one.find({name:{'$regex' : 'on$', '$options' : 'i'}})
Output:
{ "_id" : ObjectId("62939a37b3a0d806d251ddaf"), "name" : "Jennifer Johnson" }
{ "_id" : ObjectId("62939a37b3a0d806d251ddb0"), "name" : "Natalie Robinson" }
{ "_id" : ObjectId("62939a37b3a0d806d251ddb1"), "name" : "John Ferguson" }
{ "_id" : ObjectId("62939a37b3a0d806d251ddb2"), "name" : "Samuel Patterson" }
$text
Performing fuzzy searches in MongoDB
using query
$text
The query does not apply to our collection_one
example collection named because it does not have a text index. Therefore, we create an index as follows.
Sample code:
> db.collection_one.createIndex({name:"text"});
If the specified collection does not exist, the above statement will also create it. Remember that we can create an index on one or more fields separated by commas.
See the following example.
db.collection_name.createIndex({name:"text", description:"text"});
After creating the index, we can do a fuzzy search as shown below.
Sample code:
> db.collection_one.find({ $text: { $search: "Mehvish" } } )
Output:
{ "_id" : ObjectId("62939a37b3a0d806d251ddae"), "name" : "Mehvish Ashiq" }
Fuse.js
Perform fuzzy search in MongoDB
using JavaScript 's
Sample code ( fuzzysearch.js
file code):
const Fuse = require('fuse.js')
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("FuseFuzzySearch");
var personObj = [
{ name : 'Mehvish Ashiq'},
{ name : 'Jennifer Johnson'},
{ name : 'Natalie Robinson'},
{ name : 'John Ferguson'},
{ name : 'Samuel Patterson'},
{ name : 'Salvatore Callahan'},
{ name : 'Mikaela Christensen'}
];
dbo.collection("person").insertMany(personObj, function(err, res) {
if (err) throw err;
});
const options = {
includeScore: true,
keys: ['name']
}
const fuse = new Fuse(personObj, options);
const result = fuse.search('jahson');
console.log(result);
db.close();
});
Output:
[
{
item: { name: 'Jennifer Johnson', _id: 6293aa0340aa3b21483d9885 },
refIndex: 1,
score: 0.5445835311565898
},
{
item: { name: 'John Ferguson', _id: 6293aa0340aa3b21483d9887 },
refIndex: 3,
score: 0.612592665952338
},
{
item: { name: 'Natalie Robinson', _id: 6293aa0340aa3b21483d9886 },
refIndex: 2,
score: 0.6968718698752637
},
{
item: { name: 'Samuel Patterson', _id: 6293aa0340aa3b21483d9888 },
refIndex: 4,
score: 0.6968718698752637
}
]
In this code example, we first imported fuse.js
the library. Next, we connected to MongoDB.
If not connected for any reason, throw an error. Otherwise, create a FuseFussySearch
database named .
We then create an personObj
object called that contains person
all the documents we want to insert into the collection. If there are any problems inserting the data, errors will be generated.
Create Fuse
an object of , pass an array of objects keys
and with and to perform a fuzzy search and get the results, as shown above.includeScore
personObj
options
Here, keys
specify the field on which the search will be performed. includeScore
is optional, but it is better to have it because it tells the match score.
If it is 0
, the program found a perfect match, while 1
a score of indicates a complete mismatch. You can find all the options here.
Finally, don't forget to close the connection.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
List all collections in MongoDB Shell
Publish Date:2025/04/29 Views:156 Category:MongoDB
-
When using MongoDB , there are several ways to list the collections in the database. This article will discuss four different ways to get a list of collections in a MongoDB database. These methods are as follows: show collections List all c
Querying for non-null values in MongoDB
Publish Date:2025/04/29 Views:139 Category:MongoDB
-
This MongoDB article will explain how to query for non-null values in MongoDB. To query for non-null values, you can use $ne the operator and $eq the operator and then specify the desired value to query. This article shows the readers
Shutting down with code:100 error in MongoDB
Publish Date:2025/04/29 Views:53 Category:MongoDB
-
This MongoDB tutorial will teach you to fix the error on different operating systems shutting down with code:100 . It will also talk about the root cause of why this issue occurs. shutting down with code:100 Errors in MongoDB As we all know
SELECT COUNT GROUP BY in MongoDB
Publish Date:2025/04/29 Views:74 Category:MongoDB
-
In this article, we will discuss the functions in MongoDB. Also, we will point out the aggregation functions in detail. We will explain in detail the different ways to count and sort multiple and single fields of Group in MongoDB. Operation
Differences between MongoDB and Mongoose
Publish Date:2025/04/29 Views:80 Category:MongoDB
-
This MongoDB article will discuss the differences between MongoDB and Mongoose. Unfortunately, most beginners tend to confuse these two concepts when they start developing applications and use MongoDB as their backend. MongoDB has its own s
Install MongoDB using Homebrew
Publish Date:2025/04/29 Views:161 Category:MongoDB
-
MongoDB is a well-known unstructured database management system that can handle large amounts of data. It is a document-oriented database system and belongs to the NoSQL family (non-SQL). Data and records are stored as documents that look a
Create a MongoDB dump of the database
Publish Date:2025/04/29 Views:62 Category:MongoDB
-
In this MongoDB article, you’ll get a walkthrough of Mongodump and Mongorestore , how to use them, and some simple examples of backing up and restoring your collections using both tools. mongodump Commands in MongoDB Mongodump is a tool t
Get the size of the database in MongoDB
Publish Date:2025/04/29 Views:88 Category:MongoDB
-
When working in MongoDB, do you know the size of your database? Today, we will learn how to get the size of a database in MongoDB using show dbs the command and the method. db.stats() Get the size of the database in MongoDB We can show dbs;
Grouping values by multiple fields with MongoDB
Publish Date:2025/04/29 Views:99 Category:MongoDB
-
MongoDB Group by Multiple Fields is used to group values by multiple fields using various methods. One of the most efficient ways to group various fields present in MongoDB documents is by using $group the operator, which helps in per