Home > Net >  PyMongo insert an object into an already existing array in a Document
PyMongo insert an object into an already existing array in a Document

Time:03-14

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?

CodePudding user response:

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

Maybe the answers for this question will help you.

  • Related