Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

400
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!