Search code examples
pythonmongodbpymongofastapi

PyMongo insert an object into an already existing array in a Document


I want to insert a new object into an array in mongodb everytime a post api request takes place. I am using python and pymongo along with fastapi. Consider this as an example:

id1: ObjectId(...)
id2: ObjectId(...)
messages: []

what I want to do is... Everytime an api request takes place a message be added to the messages array. Like this:

id1: ObjectId(...)
id2: ObjectId(...)
messages: [
  "Hello"
]

What would be the correct way to do so with pymongo?


Solution

  • You may use the update method with the $push operator.

    Maybe the answers for this question will help you.