Search code examples
pythonpython-3.xmongodbpymongo

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}
    ]
}

Solution

  • 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)