Using regular expressions for querying MongoDB documents

Ladies and gents, here’s one fairly short hint for anyone wondering how to query documents in mongodb using regular expressions. Let’s get straight to the point:

Let’s start by inserting couple of documents (using mongodb shell) which we’ll use for querying afterwards:

db.developers.insertMany([
    { "name" : "John", "languages" : ["java", "php", "javascript"] },
    { "name" : "Johnny", "languages" : ["java", "c", "c++"] },
    { "name" : "Jim", "languages" : ["node", "java"] }
]);

Now, when we run the following command in shell:

db.developers.find()

Command output confirms all test documents are successfully stored:

{
	"_id" : ObjectId("587e6ec738cbd11c2dc46932"),
	"name" : "John",
	"languages" : [
		"java",
		"php",
		"javascript"
	]
}
{
	"_id" : ObjectId("587e6ec738cbd11c2dc46933"),
	"name" : "Johnny",
	"languages" : [
		"java",
		"c",
		"c++"
	]
}
{
	"_id" : ObjectId("587e6ec738cbd11c2dc46934"),
	"name" : "Jim",
	"languages" : [
		"node",
		"java"
	]
}

Now, say you want to find all documents that have field name starting with some particular value, let’s say “Joh”. The way to do is pretty straightforward:

db.developers.find({ name : { $regex : /^Joh.*/ } }).pretty()

Command output confirms we matched correct document(s):

{
	"_id" : ObjectId("587e6ec738cbd11c2dc46932"),
	"name" : "John",
	"languages" : [
		"java",
		"php",
		"javascript"
	]
}
{
	"_id" : ObjectId("587e6ec738cbd11c2dc46933"),
	"name" : "Johnny",
	"languages" : [
		"java",
		"c",
		"c++"
	]
}

We could also try matching documents having some field ending with particular value, let’s say “im”, just by doing something like:

db.developers.find({ name : { $regex : /^.*im$/ } }).pretty()

which would match Jim in our case:

{
"_id": ObjectId("587e6ec738cbd11c2dc46934"),
"name": "Jim",
"languages": [
"node",
"java"
]
}

Regular expressions are sometimes the only way to go for particular problem sets, so I hope this helps understanding mongodb APIs dealing with regular expressions.

Stay tuned and don’t forget to subscribe!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s