当我们尝试向 documentDB 插入小整数值时,假设为 45。 它已在 documentDB 中仅保存为整数/数字值。
但我希望将其保存为 NumberLong,无论其值是小还是长。
我尝试过添加
{"$numberLong": str(int_value)}
但是在插入文档数据库时出现异常。
Document can't have $ prefix field names: $numberLong
我正在使用 insert_many() 因为我必须保存一组记录。
我理解你的问题,我将提供有关如何使用 Python 和 pymongo 在 MongoDB 中以 NumberLong 形式插入小整数值的指导。
您是对的,插入数据时不能直接在文档中使用“$numberLong”字段名称。相反,您可以通过手动创建 BSON 文档来实现此目的。具体方法如下:
from pymongo import MongoClient
# Connect to your MongoDB instance
client = MongoClient('mongodb://localhost:27017')
# Select your database and collection
db = client['your_db_name']
collection = db['your_collection_name']
# Your small integer value
int_value = 45
# Create a document with the NumberLong format
document = {
"your_field_name": {"$numberLong": str(int_value)}
}
# Insert the document into the collection
collection.insert_one(document)
在此代码中:
insert_one()
将文档插入集合中。如果需要插入多条记录,可以使用循环。只需确保相应地修改每条记录的
document
即可。
这样,即使整数值很小,它也会在 MongoDB 集合中保存为 NumberLong。