简体   繁体   中英

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.

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.

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".

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?

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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