Performing regex Queries with PyMongo?


PyMongo is a Python distribution containing tools for working with MongoDB. To perform regex queries with PyMongo, the syntax is as follows −

db.yourCollectionName.find({'yourCollectionName':{'$regex':'^yourWords'}}).pretty();

The above syntax will give all those documents that start from a specific word.

To understand the syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.performRegex.insertOne({"ClientName":"Larry","ClientFolderInformation":[
   "Folder 1","Folder 2","Folder 3","Folder 4","Folder 5"], "MainFolderLocation":"/MainFolder/Details/ClientFolder" });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a8b186cea1f28b7aa07f2")
}
> db.performRegex.insertOne({"ClientName":"Larry","ClientFolderInformation":[
   "ClientFolder 1","ClientFolder 2","ClientFolder 3","ClientFolder 4","ClientFolder 5"],
   "MainFolderLocation":"/MainFolder/Details/ClientFolder" });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a8b1d6cea1f28b7aa07f3")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.performRegex.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c8a8b186cea1f28b7aa07f2"),
   "ClientName" : "Larry",
   "ClientFolderInformation" : [
      "Folder 1",
      "Folder 2",
      "Folder 3",
      "Folder 4",
      "Folder 5"
   ],
   "MainFolderLocation" : "/MainFolder/Details/ClientFolder"
}
{
   "_id" : ObjectId("5c8a8b1d6cea1f28b7aa07f3"),
   "ClientName" : "Larry",
   "ClientFolderInformation" : [
      "ClientFolder 1",
      "ClientFolder 2",
      "ClientFolder 3",
      "ClientFolder 4",
      "ClientFolder 5"
   ],
   "MainFolderLocation" : "/MainFolder/Details/ClientFolder"
}

Here is the query to perform regex.

Case 1 − The below query gives all documents which starts from the word ‘ClientFolder’ −

> db.performRegex.find({'ClientFolderInformation':{'$regex':'^ClientFolder'}}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c8a8b1d6cea1f28b7aa07f3"),
   "ClientName" : "Larry",
   "ClientFolderInformation" : [
      "ClientFolder 1",
      "ClientFolder 2",
      "ClientFolder 3",
      "ClientFolder 4",
      "ClientFolder 5"
   ],
   "MainFolderLocation" : "/MainFolder/Details/ClientFolder"
}

Case 2 − The below query gives all documents which starts from word ‘Folder’ −

> db.performRegex.find({'ClientFolderInformation':{'$regex':'^Folder'}}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c8a8b186cea1f28b7aa07f2"),
   "ClientName" : "Larry",
   "ClientFolderInformation" : [
      "Folder 1",
      "Folder 2",
      "Folder 3",
      "Folder 4",
      "Folder 5"
   ],
   "MainFolderLocation" : "/MainFolder/Details/ClientFolder"
}

Updated on: 30-Jul-2019

816 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements