Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

410
Vistas
In pymongo: How can I append new dict in an existing array

I found multiple tutorials about pushing a new element on pymongo array, but unfortunately, none of these worked for me.

I have a document something like this

{
    "_id": "14487152",
    "added_by": [
        {"name": "Gumi", "user_id": 70658401}
    ]
}

and this is what I am doing to insert a new dict in added_by array:

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)

but by doing this, It creates a new document and starts appending something like this

{
    "_id": {
        "_id": "14487152",
        "added_by": [
            {"name": "Gumi", "user_id": 70658401}
        ]
    },
    "added_by": [
        [
            {"name": "Harshil", "user_id": 7258757}
        ]
    ]
}

So what exactly do I want to achieve? -- I want to append {"name": "Gumi", "user_id": 70658401} in existing document inside "added_by"

Here is the output I am expecting

{
    "_id": "14487152",
    "added_by": [
        {"name": "Gumi", "user_id": 70658401},
        {"name": "Harshil", "user_id": 7258757}
    ]
}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

i 'll write something like this:

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)
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda