简体   繁体   English

将 MongoDB 中的所有文档从字符串修改为列表

[英]Modify all documents in MongoDB from string to list

Good evening,晚上好,

I have a MongoDB database with a few million entries, and one is a list of dictionaries, but formatted and stored as a string.我有一个 MongoDB 数据库,其中包含几百万个条目,其中一个是字典列表,但已格式化并存储为字符串。

key: "[{'x': 'y'}, {'a': 'b'}]"

I'm wanting to change this in all documents in to a list of dictionaries, rather than the string.我想在所有文档中将其更改为字典列表,而不是字符串。

 key: [{'x': 'y'}, {'a': 'b'}]

I can individually change each one using json.loads, however I'm not sure on the best way to iterate through the whole DB.我可以使用 json.loads 单独更改每一个,但是我不确定迭代整个数据库的最佳方法。

I'm assuming something along these lines:我假设以下几点:

collection.update_many({}, {"$set": {"$key": jason.loads("$key")}})

If I do this, I just change all of the values of the "key" key, to "$key".如果这样做,我只需将“key”键的所有值更改为“$key”。

The only way I can see to solve easily is to do a find({}), iterate through the cursor and do a collection.update_one after manipulating the string... but there must be a way to reference the key within a single update_many instruction?我认为可以轻松解决的唯一方法是进行查找({}),遍历 cursor 并在操作字符串后执行 collection.update_one ......但必须有一种方法可以在单个 update_many 中引用键操作说明?

As a separate note, what's the best way to clone a DB incase I feck it up by running an update with the wrong result?作为单独的说明,克隆数据库的最佳方法是什么,以防我通过运行结果错误的更新来搞砸它? I don't really want to risk a lot of web scraping on my ineptitude!我真的不想冒很多 web 刮我无能的风险!

As far as I know the only way to do this transformation is on the client side, ie you need to retrieve each value, transform it on the client side and update it using find-and-modify.据我所知,进行这种转换的唯一方法是在客户端,即您需要检索每个值,在客户端对其进行转换并使用查找和修改对其进行更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM