skip to Main Content

How to update dict within alot of other dicts without changing the dicts around that dict in pymongo

Im using flask with this aswell, which is why there is request.form.get() in this and why the code below has indent, i just got rid of the stuff that wasnt relevant.

      if request.form.get("name") and request.form.get("link"):
        db.update_one(
          {
            "name":request.cookies.get("x-session-name")
          },
          {
            "$set":{
              "settings":{
                "profile": {
                  "links":{
                    request.form.get("name"):request.form.get("link")
                  }
                }
              }
            }
          }
        )

What I want:

"_id": {"$oid": "644c642274116376d944b39"},
"name": "John_Doe",
"password": "$2b$12$Iggpw3gd94oifZg1YqQiVeWalpRjtKbG3/MoYPVxRefceye2cRJfm",
"email": "$2b$12$G5YMsfVnMAeMlcKuUnQBWOai8S8XQx710AECLVZ0rY.wJOlrtxkBG",
"settings": {
  "dob": {
    "year": 1990,
    "month": 11,
    "day": 10
  },
  "profile": {
      "bio": "My bio",
      "status": "status",
      "expiry": "N",
      "badges": [
        "beta",
        "staff",
        "verified"
      ],
      "links": {
        "my cool site": "https://example.net/coolstuff",
        "my cooler site": "https://example.com/coolerstuff"
      }
      "picture": {
        "active": true,
        "meta": "base64 nonesense"
      }

What I get:


{
  "_id": {
    "$oid": "644c642274116376d944b39"
  },
  "name": "John_Doe",
  "password": "$2b$12$Iggpw3gd94oifZg1YqQiVeWalpRjtKbG3/MoYPVxRefceye2cRJfm",
  "email": "$2b$12$G5YMsfVnMAeMlcKuUnQBWOai8S8XQx710AECLVZ0rY.wJOlrtxkBG",
  "settings": {
    "profile": {
      "links": {
        "my cooler site": "https://example.com/coolerstuff"
      }
    }
  }
}

Ive tried $push aswell, but it just created an array which doesnt help me here.

2

Answers


  1. Chosen as BEST ANSWER

    Using @rickhg12hs' response i managed to come up with a solution using the brackets

    db.update_one(
      {
        "name": request.cookies.get("x-session-name")
      },
            [
              {
                "$set": {
                  "settings": {
                    "profile": {
                      "links": {
                        request.form.get("name"): request.form.get("link")
                      }
                    }
                  }
                }
              }
            ])
    

  2. If you use a pipeline in the update, it seems to work as you want.

    db.update_one({
      "name":request.cookies.get("x-session-name")
    },
    [
      {
        "$set": {
          "settings": {
            "profile": {
              "links": {
                request.form.get("name"): request.form.get("link")
              }
            }
          }
        }
      }
    ])
    

    Try it on mongoplayground.net.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search