Home > front end >  Searching using pymongo from mongodb
Searching using pymongo from mongodb

Time:04-22

I am using a flask application to query the data from mongodb. Document from the mongodb is in the following format.

[{'organization_name': 'Example 1', 'date': '2021-10-15', 'url': 'https://www.example1.com/events/performances/641/2019-10-13/'}, {'organization_name': 'Example 2', 'date': '2021-10-21', 'url': 'https://file2.org/masterworks'}, {'organization_name': 'Example 3', 'date': '2021-10-21', 'url': 'https://file2.org/masterworks2'}]

Right now the query and search based on url is performing like this

    filter_stuff = {'url': 1, 'organization_name': 1, 'date':1, '_id': 0}
    data = eventcol.find({'url': url}, filter_stuff)

Here the search only works for exact complete url. How can the search be possible like if any part of url is given, all those data having that part is returned as result.

If search is file2 then the result be documents of https://file2.org/masterworks and https://file2.org/masterworks2 and if search is events then the result be https://www.example1.com/events/performances/641/2019-10-13/

CodePudding user response:

Could you do something like this?

from pymongo import MongoClient

client = MongoClient()
db = client.test

def main(search_string):
    collection = db.eventcol
    for doc in collection.find({"url": {"$regex": search_string}}):
        print(doc)
  • Related