0

我正在尝试将一个子集合添加到我的 mongodb 数据库中,该数据库称为 FootballDB,在这个数据库中有两个集合;球队和比赛。

我正在尝试添加到团队集合中,特别是我正在尝试在其中创建一个子集合,称为:

"players" : {"_id" : ObjectId(),
            "name" : "<name>",
            "number" : <num>,
            "position" : "<pos>"
}

这是团队集合当前的外观:

{
  "clubs": [
    {
      "name": "Watford FC",
      "code": "WAT",
      "country": "England"
    },
    {
      "name": "AFC Bournemouth",
      "code": "BOU",
      "country": "England"
    },
    {
      "name": "Cardiff City FC",
      "code": "CAR",
      "country": "Wales"
    },
    {
      "name": "Huddersfield Town AFC",
      "code": "HUD",
      "country": "England"
    },
    {
      "name": "Burnley FC",
      "code": "BUR",
      "country": "England"
    },
... 
}

目前,这是我将玩家添加到子集合的代码:

from bson import ObjectId
from pymongo import MongoClient
import random
import json
import names

client = MongoClient("mongodb://127.0.0.1:27017")
db = client.FootballDB
teams = db.teams

positions = [\
        'Goalkeeper',
        'Defender',
        'Midfielder',
        'Striker'
]
clubs = open('PLClub1819.json')
data = json.load(clubs)
for x in data['clubs']:
    for i in range(15):
        player = {
            "_id" : ObjectId(),
            "name" : names.get_full_name(gender='male'),
            "number" : random.randint(1,30),
            "position" : random.choice(positions)

        }
        teams.update_one({"_id" : x["_id"]}, {"$push": {"players" : player}})

但是,每当我运行它并尝试将其添加到数据库时,我都会收到以下错误:

  File "/XXXXX", line 28, in <module>
    teams.update_one({"_id" : x["_id"]}, {"$push": {"players" : player}})
KeyError: '_id'

我怀疑这是因为每个俱乐部都没有“_id”值,但是我需要更清楚,所以我正在接触更广泛的社区

对于这些问题的帮助将不胜感激 - 在此先谢谢大家!

4

1 回答 1

0

我的解决方案:删除集合: db.<collection_name>.drop()

并添加以下内容,我可以获得每个俱乐部的“_id”

def create_db():
    clubs = open('PLClub1819.json')
    data = json.load(clubs)

    for i in data['clubs']:
        teams.insert_one(i)

    matches = db.matches
    games = open('PLMatch1819.json')
    data2 = json.load(games)
    for i in data2['matches']:
        matches.insert_one(i)

我还将以下代码更改为:

positions = [ \
        'Goalkeeper',
        'Defender',
        'Midfielder',
        'Striker'
    ]

for x in teams.find():
    for i in range(15):
        player = {
            "_id": ObjectId(),
            "name": names.get_full_name(gender='male'),
            "number": random.randint(1, 30),
            "position": random.choice(positions)

        }
        teams.update_one({"_id": x["_id"]}, {"$push": {"players": player}})
于 2021-11-08T22:17:55.217 回答