简体   繁体   English

PyMongo:使用$ push通过引用另一个文档来更新现有文档

[英]PyMongo: Using $push to update an existing document with a reference to another document

I have a teams collection and a players collection. 我有球队收藏和球员收藏。 I am trying to insert documents into the teams* collection from the **players collection using $push. 我正在尝试使用$ push将文档从players集合中的team *集合中插入。

Here are the data models for both: 这是两者的数据模型:

Teams: 团队:

        {
            "team_id": 1,
            "team_name": team_name,
            "general_manager": general_manager,
            "players": [

            ]
        }

Players: 玩家:

        {
            "_id": "5c076550c779ce4fa2d4c9fd"
            "first_name": first_name,
            "last_name": last_name,
        }

Here is the code I'm using: 这是我正在使用的代码:

        player = players.find_one({ "$and": [
        {"first_name": first_name},
        {"last_name": last_name}] })


    teams.update(
        {"team_name": team_name},
        {"$push":
             {"players": {
                 "$ref": "players",
                 "$id": player["_id"],
                 "$db": db
             }}})

When I execute this, I get the following error message: 执行此操作时,出现以下错误消息:

pymongo.errors.WriteError: Found $id field without a $ref before it, which is invalid. pymongo.errors.WriteError:找到$ id字段,前面没有$ ref,这是无效的。

What am I doing wrong? 我究竟做错了什么? Thanks in advance! 提前致谢!

I simplified your queries a bit. 我简化了您的查询。 Try below (explanation in comments) 尝试以下(注释中的解释)

//Locate the player record
player = players.find_one({"first_name": first_name,"last_name": last_name})

//push this into the "players" array of the team
teams.update_one({"team_name": team_name},
    {"$push":  {"players":  player } } 
)

I used update_one instead of update, as I assume you only need to update one document in the teams collection. 我使用了update_one而不是update,因为我假设您只需要更新team集合中的一个文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM