Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find substrings in PyMongo

I wanted to find sub-strings within a field in MongoDB using PyMongo.

The following query works fine and is what I require:

db.collection.find({ "Animal": /cat|Dog/i})

However, if I try passing the value /cat|Dog/i as a string in Python, it doesn't work.

Is there a way to replicate the query in PyMongo?

Note: /cat|Dog/i is value of field from another collection. It is in the form 'cat Dog'. Basically, I want to match substrings in one field with substrings in another.

like image 891
Vaulstein Avatar asked Nov 25 '15 15:11

Vaulstein


People also ask

How do I search for a string in MongoDB?

Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.

What does PyMongo find return?

PyMongo read all data The find method selects documents in a collection or view and returns a cursor to the selected documents. A cursor is a reference to the result set of a query.

What does Insert_one return PyMongo?

When a document is inserted a special key, "_id" , is automatically added if the document doesn't already contain an "_id" key. The value of "_id" must be unique across the collection. insert_one() returns an instance of InsertOneResult .

What is MongoClient in PyMongo?

Python PyMongo MongoClient allows Developers to establish a connection between their Python application and MongoDB to manage data in a NoSQL Database. Python PyMongo MongoClient makes it easier for Developers to access all the features of the NoSQL Database and build a scalable and flexible Python application.


1 Answers

You need to compile your regular expression pattern using re.compile() function into a regular expression object.

import re

pat = re.compile(r'cat|Dog', re.I)
db.collection.find({ "Animal": {'$regex': pat}})
like image 111
styvane Avatar answered Oct 06 '22 01:10

styvane