Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pymongo UUID search not returning documents that definitely exist

Trying to define a function in python that can search for a given UUID like so:

def getid(in_id):
    return list(CollectionVar.find({"_id":UUID(in_id)}))

And passing in a UUID. I can take a UUID I know exists from Studio 3T like so:

db.getCollection("CollectionName").find({"_id":UUID("5002aa11-eeb7-4e68-a121-dd51497d2572")})

And the above query returns precisely one document. That same UUID in the python query returns absolutely nothing. I can find documents on other (non UUID) fields easily enough, for example the following works fine on that same document from earlier:

def getname(fn,sn):
    return list(CollectionVar.find({"Firstname":re.compile(fn, re.IGNORECASE), "Surname":re.compile(sn, re.IGNORECASE)}))

This seems like a problem with the uuid.UUID class rather than a pymongo issue? Can anyone see the problem?

PyMongo Version 3.6.1

like image 501
MB141 Avatar asked Aug 31 '25 17:08

MB141


1 Answers

The issue is that PyMongo uses a legacy method of encoding/decoding UUID values by default. You probably want to configure the PyMongo client to use the more modern, cross-language compatible "standard" UUID representation:

client = MongoClient(MONGODB_URI, uuidRepresentation="standard")

Now you should be able to query directly using Python uuid.UUID instances:

from uuid import UUID

items = client["item_database"]["items"].find_one({
    "uuid": UUID("187382af-1369-43e6-a0ba-d345886c986c")
})
like image 199
Hubro Avatar answered Sep 02 '25 05:09

Hubro