Search code examples
mongodbfindpymongosubdocument

Why doesn't this pymongo subdocument find work?


I'm looking at using mongodb and so far most things that I've tried work. But I don't know why this find doesn't work.

col = db.create_collection("test")
x = col.insert_many([
    {"item": "journal", "qty": 25, "size": {"h": 14, "w": 21, "uom": "cm"}, "status": "A"},
    {"item": "notebook", "qty": 50, "size": {"h": 8.5, "w": 11, "uom": "in"}, "status": "A"},
    {"item": "paper", "qty": 100, "size": {"h": 8.5, "w": 11, "uom": "in"}, "status": "D"},
    {"item": "planner", "qty": 75, "size": {"h": 22.85, "w": 30, "uom": "cm"}, "status": "D"},
    {"item": "postcard", "qty": 45, "size": {"h": 10, "w": 15.25, "uom": "cm"}, "status": "A"}
])

cursor = col.find({"size": {"h": 14, "w": 21, "uom": "cm"}})
if cursor.retrieved == 0:
    print("found nothing")          # <<<<<<<<< prints this

Solution

  • I was thinking that cursor.retrieved was non zero if it found something. I guess not. I found that this works:

    lst = list(cursor)
    print(lst)
    
    cursor.rewind()
    print(list(cursor))
    
    if len(lst) != 0:
        for d in lst:
            print(d)