英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论