I often forget it together with postgreSQL, so I will write it down. Please refer to How to use pymongo for detailed operations such as specifying conditions.
from pymongo import MongoClient
mongo_server = 'localhost'
mongo_port = '27017'
mongo_database_name = 'database'
mongo_collection_name = 'collection'
def displ
ay_data(collection, mongo_filter=None):
data = collection.find(filter=mongo_filter)
for elem in data:
print(elem)
def insert_data(collection, data):
collection.insert_one(data)
if __name__ =='__main__':
mongoclient = MongoClient('mongodb://' + mongo_server + ':' + mongo_port + '/')
db = mongoclient[mongo_database_name]
collection = db[mongo_collection_name]
#Data entry
for i in range(10):
data = {'count' :i}
insert_data(collection, data)
#Data display
display_data(collection)
Execution result
{'_id': ObjectId('5e168f7828ba5616d6873582'), 'count': 0}
{'_id': ObjectId('5e168f7828ba5616d6873583'), 'count': 1}
{'_id': ObjectId('5e168f7828ba5616d6873584'), 'count': 2}
{'_id': ObjectId('5e168f7828ba5616d6873585'), 'count': 3}
{'_id': ObjectId('5e168f7828ba5616d6873586'), 'count': 4}
{'_id': ObjectId('5e168f7828ba5616d6873587'), 'count': 5}
{'_id': ObjectId('5e168f7828ba5616d6873588'), 'count': 6}
{'_id': ObjectId('5e168f7828ba5616d6873589'), 'count': 7}
{'_id': ObjectId('5e168f7828ba5616d687358a'), 'count': 8}
{'_id': ObjectId('5e168f7828ba5616d687358b'), 'count': 9}
Recommended Posts