如何使用 python/pymongo 向文档 DB / mongo DB 中的 NumberLong 插入小 int 值

问题描述 投票:0回答:1

当我们尝试向 documentDB 插入小整数值时,假设为 45。 它已在 documentDB 中仅保存为整数/数字值。

但我希望将其保存为 NumberLong,无论其值是小还是长。

我尝试过添加

{"$numberLong": str(int_value)} 

但是在插入文档数据库时出现异常。

Document can't have $ prefix field names: $numberLong

我正在使用 insert_many() 因为我必须保存一组记录。

pymongo long-integer python-3.9 aws-documentdb
1个回答
0
投票

我理解你的问题,我将提供有关如何使用 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)

在此代码中:

  1. 使用 MongoClient 连接到您的 MongoDB 实例。
  2. 选择您的数据库和集合。
  3. 定义您的小整数值(在本例中为 45)。
  4. 创建一个包含“$numberLong”格式的所需字段名称的文档,将整数转换为字符串。
  5. 使用
    insert_one()
    将文档插入集合中。

如果需要插入多条记录,可以使用循环。只需确保相应地修改每条记录的

document
即可。

这样,即使整数值很小,它也会在 MongoDB 集合中保存为 NumberLong。

© www.soinside.com 2019 - 2024. All rights reserved.