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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.