'i am using Python, MongoDB

i have this question that says :

these are the questions

how can i add a code, to return no match, if no matches are found?

i did this to answer the questions above in the image :

    import sys
from pymongo import MongoClient as mc
from pymongo import ASCENDING as asc, DESCENDING as desc


def get_coll():
    try:

        server = mc("localhost", 27017)
        moviesdb = server.lab4
        return moviesdb.movies        
    except:
        return None
moc = get_coll()
if moc:
    print("Find Movies by")
    choice = input("1.Imdb ID\n"
          "2. Plot\n"
          "3. Stop Search\n" )
    if choice == "1":
        imdb = input("Enter a IMDB ID: ")
        imdb_curs = moc.find({"imdb_id":imdb},
                                {"imdb_id":True, "title": True,"_id":False}
                             )
        imdp_list = list(imdb_curs)
        for m in imdp_list:
            print(f"{m['imdb_id']} : {m['title']}")
    elif choice == "2":
        plot_word = input("Enter a search word for plot: ").lower()

        plot_curs = moc.find({"plot" : {"$regex" : plot_word }}, {"title" :True,"_id" :False}).sort("title",asc)

        plot_list = list(filter(None,plot_curs))
        for p in plot_list:
            print((f"{p['title']}"))
    else:
        sys.exit(0)
else:
    print("Unable to Connect")


Solution 1:[1]

You can check on the returned cursor to see how many results there are:

imdb_curs.count() or plot_curs.count()

If the count is 0, you can run whatever code you want to handle no matches.

https://api.mongodb.com/python/2.7.2/api/pymongo/cursor.html#pymongo.cursor.Cursor.count

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DavidA