Python上传数据到MongoDB

huangapple go评论73阅读模式
英文:

Python upload Data in MongoDB

问题

我正在从MongoDB的JSON文件中上传数据,但我想将每5个数据点合并到Mongo的一个字段中,我正在使用这个循环:

document = {}

for key, data_point in zip(fields, data[:5]):
for sub_key, value in data_point.items():
document[f"{key}_{sub_key}"] = value

插入数据

collection.insert_one(document)


这对我来说有效,可以将5个数据点合并到一个Mongo字段中,但它只上传了前5个数据点,没有继续循环以获取我拥有的全部3170个字段,应该在Mongo中创建634个字段。
英文:

I'm uploading data from a JSON file in MongoDB but I want to take each 5 datapoints into 1 field in mongo and I'm using this loop:

document = {}

for key, data_point in zip(fields, data[:5]):
    for sub_key, value in data_point.items():
        document[f"{key}_{sub_key}"] = value

# Insert Data
collection.insert_one(document)

It works for me on getting 5 datapoints into 1 Mongo field but it only uploads the first 5 and doesn't continue looping to get all 3170 fields that I have which should create 634 fields in Mongo.

答案1

得分: 0

你正在获取前5个项目。您应该遍历每5个项目。这里是一个示例:

chunks = [data[x:x+5] for x in range(0, len(data), 5)]
for chunk in chunks:
    document = {}
    for i, data_point in enumerate(chunk):
        for sub_key, value in data_point.items():
            # 根据块的索引和sub_key创建新字段键
            document[f"{i}_{sub_key}"] = value
    # 插入数据
    collection.insert_one(document)
英文:

you are taking first 5 items. You should iterate through every 5 items. Here example:

chunks = [data[x:x+5] for x in range(0, len(data), 5)]
for chunk in chunks:
    document = {}
    for i, data_point in enumerate(chunk):
        for sub_key, value in data_point.items():
            # Create new field key based on the index of the chunk and the sub_key
            document[f"{i}_{sub_key}"] = value
    # Insert Data
    collection.insert_one(document)

huangapple
  • 本文由 发表于 2023年6月8日 17:35:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430490.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定