Encontré varios tutoriales sobre cómo insertar un nuevo elemento en la matriz de pymongo, pero desafortunadamente, ninguno de estos funcionó para mí.
tengo un documento algo asi
{ "_id": "14487152", "added_by": [ {"name": "Gumi", "user_id": 70658401} ] } y esto es lo que estoy haciendo para insertar un nuevo dict en la matriz added_by :
def find_product(self, _id): # Find by Id data = self.collection.find_one({"_id": _id}) return data def add_new_product(self): self.collection.update_one( {"_id": self.find_product(_id=product['_id'])}, {"$push": {"added_by": [{"name": "Harshil", "user_id": 7258757}]}}, upsert=False)pero al hacer esto, crea un nuevo documento y comienza a agregar algo como esto
{ "_id": { "_id": "14487152", "added_by": [ {"name": "Gumi", "user_id": 70658401} ] }, "added_by": [ [ {"name": "Harshil", "user_id": 7258757} ] ] } Entonces, ¿qué quiero lograr exactamente? -- Quiero agregar {"name": "Gumi", "user_id": 70658401} en el documento existente dentro "added_by"
Aquí está la salida que estoy esperando
{ "_id": "14487152", "added_by": [ {"name": "Gumi", "user_id": 70658401}, {"name": "Harshil", "user_id": 7258757} ] }Voy a escribir algo como esto:
def add_new_product(self): data = self.find_product(_id=product['_id']) newvalue = {"$push": {'added_by': {"name": "Harshil", "user_id": 7258757}}} self.collection.update_one({"_id": data['_id']}, newvalue)