I have a MongoDB database with the following structure (simplified for the question's sake):
User:
"id": int
"aquarium": Aquarium[]
Aquarium:
"name": str
"fish": Fish[]
I have access to:
My purpose is to push the Fish type object (refered to as "obj" in the code) into the target Aquarium's fish array.
So far I have attempted to achieve this with the following code:
users_db.find_one_and_update
(
{
"_id": ObjectId(str(id)),
"aquarium.name": aquarium_name
},
{
"$push": {"aquarium.fish": obj}
}
)
This was, however, unsuccessful. The following error was returned:
I have reviewed numerous other question, such as this one, however I could not find a question which simultaneously demands a query dependent on both the inner and outer layer and insertion into the inner layer at the same time. It is hard for me to tell whether the issue comes from an invalid query or an invalid update operation, therefore I am unsure of which direction to go from this point.
Does anybody know what could be the cause of this? I'd appreciate any help.
While Yong's answer was very helpful and got me closer to the answer, ultimately it didn't entirely solve my problem.
What did, however, solve my issue, was using array_filters to find the appropriate entry.
The functional code is as below:
users_db.find_one_and_update(
{"_id": ObjectID(str(id))},
{"$push": {"aquarium.$[a].fish": obj}},
array_filters=[{"a.name": aquarium_name}],
)