PyMongo save List of dict in subfield with own ObjectId for every dict entry

Advertisements

I’m creating a list of Objects in my script, and want so save/update them in a subfield of an mongo db document.

My Objects looks like this:

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

in my process i’m generating a list of this objects

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

than later i want to save or update this in my 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
    )

this code works in principle, but the objects under "player" are saved without an ObjectId. And i want an ObjectId for every Object under "player".

As Example

{
    _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"
      }
    ]
}

How to insert a list of objects (dict’s) with ObjectIds in a subfield of a document?

>Solution :

You can try this solution:

from bson.objectid import ObjectId

class IndividualRating:
    def __init__(self, place=0, player="", team="", games="", legs=""):
        self._id = ObjectId()
        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__)

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
    )

Leave a ReplyCancel reply