Skip to content

Pattern matching in MongoDB with regex

In this post, you will learn how to match mongodb documents with a partial value. This is similar to pattern matching using LIKE predicate in SQL.

Finding a document in MongoDB using partial value of a field can be done using a Regular Expression instead of a string value.

The users collection has the following data.

db.users.find({})

{
	"_id": ObjectId("5e16e8a3c3775d62f3acbe72"),
	"name": "Kemba Walker",
	"username": "kwalk",
	"role": "Staff",
	"group": ["Staff"]
}
{
	"_id": ObjectId("5e203b5c5981cd83c5ae1398"),
	"name": "John Rashford",
	"username": "jrash",
	"team": "Manager",
	"group": ["Managers"]
}
{
	"_id": ObjectId("5e5e01cb3ef4456a4f739f62"),
	"name": "Jim Whitaker",
	"username": "jwhit",
	"role": "Admin",
	"group": ["Admin"]
}

Let’s say I want to find the users whose name starts with J.

db.users.find({name: /J/})



{
	"_id": ObjectId("5e203b5c5981cd83c5ae1398"),
	"name": "John Rashford",
	"username": "jrash",
	"team": "Manager",
	"group": ["Managers"]
}
{
	"_id": ObjectId("5e5e01cb3ef4456a4f739f62"),
	"name": "Jim Whitaker",
	"username": "jwhit",
	"role": "Admin",
	"group": ["Admin"]
}

If you want this find filter be case insensitve, just add i after the /

db.users.find({name: /J/i})

This will filter the users whose name starts with lowercase J (j) too.

See also  The option 'autoReconnect' is incompatible with the unified topology - Mongo Error - How to fix?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.