2016-06-11 60 views
0

我有一个包含20条记录的JSON文件。 我试图通过python将数据从JSON插入到MongoDB中(pymongo是具体的)。 以下是python代码。通过pymongo在MongoDB中插入数据时的差异

from pymongo import MongoClient 
from pprint import pprint 
import json 

# creating a mongo db client and connecting with 
# the fantasyscout database. 
# Inserting the players in the collection(table) 
# players. 
client = MongoClient() 
db = client.fantasyscout 

# Reading the data from the dumper json file 
with open("C:\\team.level.json") as db_data: 
data = json.load(db_data) 

# Reading every element in the JSON data and 
# inserting in the db. 
print len(data) 
print data[str(20)] 
for element in range(1,++len(data)): 
    db.team_level.insert(data[str(element)]) 

len(data)保存值20(通过python打印确认)。虽然运行这个脚本后,没有。插入的记录是19,并且未插入data["20"]。 将范围手动更改为(1,21)后,脚本将输入全部20条记录。 我错过了一些非常微不足道的东西。请指出我的错误。

回答

0

For循环从0到2,因此运行3次。

for x in range(0, 3): 
    print "We're on time %d" % (x) 

,这意味着你需要从0不遍历从1

reference