簡體   English   中英

如何將 integer 轉換為嵌套在 Pymongo 數組中的文檔中的字符串?

[英]How can I convert an integer to a string in a document nested in an array in Pymongo?

我有一個文檔,嵌套在 mongoDB 的一個數組中。 其中一個文檔元素是 integer 但我需要將其轉換為字符串。 我嘗試使用許多不同的方法來解決這個問題,同時使用update_one()update_many()函數。 我也嘗試過以不同的方式使用$toString$set$convert ,我什至發現了一篇嘗試使用aggregate() function 的帖子。 我的任何嘗試似乎都沒有產生任何結果。 其中一些嘗試會產生錯誤,但在大多數情況下,它似乎正在工作,直到我檢查數據並且沒有任何改變。

以下是數據的示例:

[
  {
    "_id": ObjectId("62d7e96b3348d2ed4d3f6c37"),
    "index": 2394,
    "hashDec": "17795682514039271424",
    "hashHex": "0xf6f6f6f600f0f000",
    "postList": [
      {
        "timestamp": 1659646945.456782,
        "uploadTime": 1659646903.0,
        "author": "Osinttechnical",
        "id": 1555297956483305472,
        "platform": "twitter",
        "text": ""
      },
      {
        "platform": "twitter",
        "id": 1567987802234851328,
        "author": "UAWeapons",
        "text": "#Ukraine: A Russian Ural-4320 transport truck had a a slight accident and was abandoned in #Kharkiv Oblast.",
        "timestamp": 1662672491.5861459,
        "uploadTime": 1662672398.0
      }
    ]
  }
]

這對我來說似乎最合乎邏輯:

self.allDocs = list(self.video.find({}).sort("index"))

        for index, doc in enumerate(self.allDocs):

            print(f"[{datetime.datetime.now()}] Updating doc: {doc['index']}")

            for post in doc["postList"]:

                if isinstance(post["id"], int):

                    print(f"[{datetime.datetime.now()}] Updating post: {post}")
                    self.video.update_one({"index": doc["index"],
                        "postList.$[].id": post["id"]},
                        {"$set": {"postList.$[].id": str(post["id"])}},
                        upsert=False)

有誰知道如何最好地做到這一點?

我建議您將update_many聚合管道更新功能一起使用,這允許您執行單個更新來實現此目的,而無需像您正在做的那樣將所有文檔讀入 memory 的開銷。

它看起來像這樣:

self.video.update_many({},
[
  {
    "$set": {
      "postList": {
        "$map": {
          "input": "$postList",
          "in": {
            "$mergeObjects": [
              "$$this",
              {
                "id": {
                  "$toString": {
                    "$toLong": "$$this.id"
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
])

蒙戈游樂場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM