0

I am trying to update a value of an array stored in a mongodb collection

any_collection: {
 {
  "_id": "asdw231231"
  "values": [
     {
        "item" : "a"
     },
     {
        "item" : "b"
     }
   ],
  "role": "role_one"
 },
 ...many similar
}

the idea is that I want to access values ​​and edit a value with the following code that I found in the mongodb documentation

conn.any_collection.find_one_and_update(
    {
        "_id": any_id,
        "values.item": "b"
    },
    {
        "$set": {
            "values.$.item": "new_value"  # here the error, ".$."
        }
    }
)

This should work, but I can't understand what the error is or what is the correct syntax for pymongo. The error is generated when adding "$";

jeansyo
  • 21
  • 4

1 Answers1

0

It works fine with my fastAPI.

@app.get("/find/{id}")
async def root(id: int):
    db = get_database()
    q = {'_id': 'asdw231231','values.item': 'b'}
    u = {'$set': {'values.$.item': 'new_value' }}
    c = db['any'].find_one_and_update(q, u)
    return {"message": c}

mongoplayground

YuTing
  • 6,555
  • 2
  • 6
  • 16