Bora
Bora

Reputation: 1522

UUID to NUUID in Python

In my application, I get some values from MSSQL using PyMSSQL. Python interpret one of this values as UUID. I assigned this value to a variable called id. When I do

print (type(id),id)

I get

<class 'uuid.UUID'> cc26ce03-b6cb-4a90-9d0b-395c313fc968

Everything is as expected so far. Now, I need to make a query in MongoDb using this id. But the type of my field in MongoDb is ".NET UUID(Legacy)", which is NUUID. But I don't get any result when I query with

client.db.collectionname.find_one({"_id" : id})

This is because I need to convert UUID to NUUID.

Note: I also tried

client.db.collectionname.find_one({"_id" : NUUID("cc26ce03-b6cb-4a90-9d0b-395c313fc968")})

But it didn't work. Any ideas?

Upvotes: 0

Views: 991

Answers (1)

Bernie Hackett
Bernie Hackett

Reputation: 8909

Assuming you are using PyMongo 3.x:

from bson.binary import CSHARP_LEGACY
from bson.codec_options import CodecOptions
options = CodecOptions(uuid_representation=CSHARP_LEGACY)
coll = client.db.get_collection('collectionname', options)
coll.find_one({"_id": id})

If instead you are using PyMongo 2.x

from bson.binary import CSHARP_LEGACY
coll = client.db.collectionname
coll.uuid_subtype = CSHARP_LEGACY
coll.find_one({"_id": id})

You have to tell PyMongo what format the UUID was originally stored in. There is also a JAVA_LEGACY representation.

Upvotes: 2

Related Questions