mongodb 如何在pymongo中更新大量其他字典中的字典而不改变该字典周围的字典

9w11ddsr  于 2023-05-06  发布在  Go
关注(0)|答案(2)|浏览(186)

如何在pymongo中更新大量其他字典中的字典而不改变该字典周围的字典
我也在使用flask,这就是为什么这里有request.form.get(),为什么下面的代码有缩进,我只是去掉了不相关的东西。

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")
                  }
                }
              }
            }
          }
        )

我想要的:

"_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"
      }

我得到的:

{
  "_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"
      }
    }
  }
}

我也试过$push,但它只是创建了一个数组,在这里对我没有帮助。

tp5buhyn

tp5buhyn1#

如果您在更新中使用管道,它似乎可以按您所需的方式工作。

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

mongoplayground.net上试试。

yyhrrdl8

yyhrrdl82#

使用@rickhg12hs的响应,我设法想出了一个使用括号的解决方案

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

相关问题