Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

402
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda