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.
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.
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.
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 .
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.
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}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With