Last active
November 11, 2021 18:59
-
-
Save ingo-m/38ddff43740c030c891e092ae4f9bb30 to your computer and use it in GitHub Desktop.
MongoDB insert & update demo.
This file contains 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
""" | |
MongoDB insert & update demo. | |
Create a database & collection on a local MongoDB instance, and insert & update | |
some documents. | |
""" | |
import pymongo | |
from pprint import pprint | |
# ----------------------------------------------------------------------------- | |
# *** Preparations | |
client = pymongo.MongoClient() | |
my_db = client.my_database | |
my_col = my_db['my_collection'] | |
# ----------------------------------------------------------------------------- | |
# *** Insert datapoints | |
observation_01 = { | |
'name': 'Ron', | |
'IQ': 82.2, | |
'hair_colour': 'ginger', | |
} | |
observation_02 = { | |
'name': 'Hermione', | |
'IQ': 178.5, | |
'hair_colour': 'brown', | |
} | |
response = my_col.insert_many([observation_01, observation_02]) | |
query_result = list(my_col.find({}, {'_id': False})) | |
pprint(query_result) | |
# Returns: | |
# [{'IQ': 82.2, 'hair_colour': 'ginger', 'name': 'Ron'}, | |
# {'IQ': 178.5, 'hair_colour': 'brown', 'name': 'Hermione'}] | |
# ----------------------------------------------------------------------------- | |
# *** Test 1 - update one field | |
response = my_col.update_one( | |
{'name': 'Ron'}, # Search for name = Ron | |
{'$set': {'IQ': 55.8}}, # Update only the IQ field | |
) | |
query_result = list(my_col.find({}, {'_id': False})) | |
pprint(query_result) | |
# Ron's IQ field has been updated, without changing any other fields: | |
# [{'IQ': 55.8, 'hair_colour': 'ginger', 'name': 'Ron'}, | |
# {'IQ': 178.5, 'hair_colour': 'brown', 'name': 'Hermione'}] | |
# ----------------------------------------------------------------------------- | |
# *** Test 2 - insert extra field in existing document | |
response = my_col.update_one( | |
{'name': 'Hermione'}, # Search for name = Hermione | |
{'$set': {'house': 'Gryffindor'}}, # Add a new field | |
) | |
query_result = list(my_col.find({}, {'_id': False})) | |
pprint(query_result) | |
# Adding a new field doesn't change the existing fields: | |
# [{'IQ': 55.8, 'hair_colour': 'ginger', 'name': 'Ron'}, | |
# {'IQ': 178.5, | |
# 'hair_colour': 'brown', | |
# 'house': 'Gryffindor', | |
# 'name': 'Hermione'}] | |
client.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment