Last active
December 24, 2018 18:07
-
-
Save gwbischof/095e478923977ac76ec98e5d35c35f6e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pymongo import InsertOne, DeleteOne, ReplaceOne | |
from pymongo.errors import BulkWriteError | |
from pymongo import MongoClient | |
client = MongoClient('localhost', 27017) | |
update_test = client['UpdateOne'] | |
table = update_test.table | |
# drops the table to start fresh | |
def drop_testdb(): | |
client.drop_database(update_test) | |
# Example document | |
doc_in = { | |
'append': ['one'], | |
'append2' : ['a'], | |
'uid': '1' | |
} | |
# Drop the table, insert the doc, query and print the result. | |
drop_testdb() | |
result = table.insert_one(doc_in) | |
doc_out = table.find({'uid' : '1'}) | |
print(list(doc_out)) | |
# Example document 2 | |
doc_in2 = { | |
'append': ['two', 'three', 'four'], | |
'append2': ['b', 'c', 'd'], | |
'uid': '1'} | |
# Update_one, but appending to multiple key in the same operation | |
# The append3 line appends to a key that does not exist yet. | |
# $push gives an error if you try to append to a key that exists but is not a list. | |
# I'm looking for a way to handle the situation where we have a key with a single value, | |
# and we want to convert it to a list of values and then append. | |
table.update_one({'uid' : '1'}, {'$push' : | |
{ 'append' : {'$each' : doc_in2['append']}, | |
'append2' : {'$each' : doc_in2['append2']}, | |
'append3' : {'$each' : doc_in2['append2']} | |
} | |
}, | |
upsert=True) | |
doc_out = table.find({'uid' : '1'}) | |
print(list(doc_out)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment