Skip to content

Instantly share code, notes, and snippets.

@Skycocoo
Created July 9, 2018 21:15
Show Gist options
  • Save Skycocoo/10f6dd64efa052dcdf83402e926763e1 to your computer and use it in GitHub Desktop.
Save Skycocoo/10f6dd64efa052dcdf83402e926763e1 to your computer and use it in GitHub Desktop.
Pymongo example (starter code)
# https://realpython.com/introduction-to-mongodb-and-python/
# to connect to mongodb:
# windows:
# cmd: $ "C:\Program Files\MongoDB\Server\4.0\bin\mongod.exe" --dbpath="c:\data\db"
import pymongo
from pymongo import MongoClient
# default port: client = MongoClient('mongodb://localhost:27017')
client = MongoClient()
db = client.pymongo_test
posts = db.posts
post_data = {
'title': 'Python and MongoDB',
'content': 'PyMongo is fun, you guys',
'author': 'Scott'
}
result = posts.insert_one(post_data)
print('One post: {0}'.format(result.inserted_id))
post_1 = {
'title': 'Python and MongoDB',
'content': 'PyMongo is fun, you guys',
'author': 'Scott'
}
post_2 = {
'title': 'Virtual Environments',
'content': 'Use virtual environments, you guys',
'author': 'Scott'
}
post_3 = {
'title': 'Learning Python',
'content': 'Learn Python, it is easy',
'author': 'Bill'
}
new_result = posts.insert_many([post_1, post_2, post_3])
print('Multiple posts: {0}'.format(new_result.inserted_ids))
# retrieve document
bills_post = posts.find_one({'author': 'Bill'})
print(bills_post)
print(bills_post['title'])
# # retrieve iterator of documents
# scotts_posts = posts.find({'author': 'Scott'})
# print(scotts_posts)
# for post in scotts_posts:
# print(post)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment