Search code examples
pythonarraysmongodbpymongo

Pymongo How to update specific value of row in array


I have this simple JSON in mongodb:

{
        "pwd_list": [
            {
                "pwd": "password1",
                "pwd_date": str(int(time.time()))
            },
            {
                "pwd": "password2",
                "pwd_date": str(int(time.time()))
            },
       ]
}

What I am simply trying to do is to update one of the row of the pwd_list array using an index...

I tried to use the $position of mongodb but it seems to only work with $push but I don't want to push!

I'm using pymongo.

So I tried different things like this one:

self.collection.update({"email": "email"},
            {
            "$set": {
                "pwd_list": {
                            "temp_passwd": "NEW VALUE",
                            "temp_date": "str(int(time.time()))"
                            }   
                   }
            })

But it it not working as expected. (The above example is transforming the array in object...)

If it is not possible, can I at least update the first row (always this one)?


Solution

  • You have two options when doing this. If you want to search for a specific item to change, you should do the following:

    self.collection.update({"email": "email", "pwd_list.pwd": "Password2"},
            {
            "$set": {
                "pwd_list.$": {
                            "pwd": "NEW VALUE",
                            "pwd_date": "str(int(time.time()))"
                            }   
                   }
            })
    

    If you want to change a specific item, and you know the position of the item in the array, you should do the following (in my example I am changing the first item):

    self.collection.update({"email": "email"},
            {
            "$set": {
                "pwd_list.0": {
                            "pwd": "NEW VALUE",
                            "pwd_date": "str(int(time.time()))"
                            }   
                   }
            })
    

    You can find more details about this on this page.