我需要将我拥有的一些十六进制字符串转换为UUID,并将它们存储在MongoDB中。
我尝试了以下内容:
import pymongo
import uuid
[...]
document = { '_id': 123, 'my_uuid': uuid.UUID('b7aef1d4830843750f3846b34606528f') }
my_collection.save(document)
但是这会插入一个LUUID而不是UUID。
我错过了什么吗?
答案 0 :(得分:1)
但是这会插入一个LUUID而不是UUID。
LUUID不是BSON或PyMongo类型。它只是一个名称,Robomongo uses表示存储为BSON二进制文件的UUID,子类型为3而不是子类型4.
For example the source code of UuidRepresentation class in mongodb java library:
/**
* The representation to use when converting a UUID to a BSON binary value.
* This class is necessary because the different drivers used to have different
* ways of encoding UUID, with the BSON subtype: \x03 UUID old.
*
* @since 3.0
*/
public enum UuidRepresentation {
/**
* The canonical representation of UUID
*
* BSON binary subtype 4
*/
STANDARD,
/**
* The legacy representation of UUID used by the C# driver
*
* BSON binary subtype 3
*/
C_SHARP_LEGACY,
/**
* The legacy representation of UUID used by the Java driver
*
* BSON binary subtype 3
*/
JAVA_LEGACY,
/**
* The legacy representation of UUID used by the Python driver, which is the same
* format as STANDARD, but has the UUID old BSON subtype (\x03)
*
* BSON binary subtype 3
*/
PYTHON_LEGACY
}
有关二进制子类型的更多信息,请参阅BSON spec。实际上,您正在存储UUID。如果你决定在Robomongo中看到UUID而不是LUUID,那么你可以像这样在PyMongo中切换UUID表示:
client = MongoClient(uuidRepresentation='standard')
我最近写了历史in this ticket。