mongodb PyMongo保存子字段中的字典列表,每个字典条目都有自己的ObjectId

myzjeezk  于 2023-06-29  发布在  Go
关注(0)|答案(1)|浏览(141)

我在我的脚本中创建了一个对象列表,并希望在mongo db文档的子字段中保存/更新它们。
我的对象看起来像这样:

class IndividualRating:
    def __init__(self, place=0, player="", team="", games="", legs=""):
        self.place = place
        self.player = player
        self.team = team
        self.games = games
        self.legs = legs

在我的进程中我生成了一个对象列表

ratings = []
for row in rows:
    rating = IndividualRating()
    # defining here the values
    ratings.append(rating.__dict__)

比以后我想保存或更新这在我的mongodb

def save_ratings(league_id, season_id, ratings):
    database.individualratings.update_one(
    {
        "seasonId": season_id,
        "leagueId": league_id
    },
    {
        "$setOnInsert": {
            "seasonId": season_id,
            "leagueId": league_id
        },
        "$set": {
            "player": ratings
        }
    },
    upsert=True
    )

这段代码原则上可以工作,但是“player”下的对象没有ObjectId。我想要一个ObjectId下的每个对象“播放器”。
作为示例

{
    _id: ObjectId('someLongId'),
    seasonId: 56267,
    leagueId: 27273,
    player: [
      {
          <- Here should be an ObjectId
          place: 1,
          player: "Some Player Name",
          team: "Some Team Name",
          games: "2:0",
          legs: "10:0"
      },
      {
          <- Here should be an ObjectId
          place: 2,
          player: "Some Player Name",
          team: "Some Team Name",
          games: "2:0",
          legs: "10:0"
      }
    ]
}

如何在文档的子字段中插入具有ObjectIds的对象列表(字典)?

anhgbhbe

anhgbhbe1#

因为你的IndividualRating对象不是作为根文档插入的,所以没有理由,为什么你的mongodb驱动程序应该为每个数组成员生成一个ObjectId。如果您真的需要IndividualRating对象的这个惟一标识符,那么您需要自己生成这个id。
添加以下导入:

from bson.objectid import ObjectId

将以下变量添加到IndividualRating对象:

self._id = ObjectId()

对于每个对象,将生成唯一的ID。

相关问题