
Pythonを使用して、MongoDBにアクセスします。
pymongoのインストールする!
pymongoをインストールします。
$ python -m pip install pymongo Collecting pymongo Using cached https://files.pythonhosted.org/packages/11/88/dd1f8c4281a60791b043f55e338d0521049208f21e3de19ddc9c160dbbef/pymongo-3.7.1-cp36-cp36m-manylinux1_x86_64.whl Installing collected packages: pymongo Successfully installed pymongo-3.7.1
pymongoを使用してMongoDBにアクセスする!
pymongoを使用してMongoDBにアクセスしてみましょう。
$ python
Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pymongo import MongoClient
>>> client = MongoClient()
>>> db = client.test_database
>>> collection = db.test_collection
>>> import datetime
>>> post = {"author": "Mike",
... "text": "My first blog post!",
... "tags": ["mongodb", "python", "pymongo"],
... "date": datetime.datetime.utcnow()}
>>> posts = db.posts
>>> post_id = posts.insert_one(post).inserted_id
>>> post_id
ObjectId('5ba70fb1c9bb161d3c03bb4a')
>>> db.collection_names(include_system_collections=False)
['posts']
>>> import pprint
>>> pprint.pprint(posts.find_one())
{'_id': ObjectId('5ba70fb1c9bb161d3c03bb4a'),
'author': 'Mike',
'date': datetime.datetime(2018, 9, 23, 3, 58, 27, 70000),
'tags': ['mongodb', 'python', 'pymongo'],
'text': 'My first blog post!'}
>>> pprint.pprint(posts.find_one({"author": "Mike"}))
{'_id': ObjectId('5ba70fb1c9bb161d3c03bb4a'),
'author': 'Mike',
'date': datetime.datetime(2018, 9, 23, 3, 58, 27, 70000),
'tags': ['mongodb', 'python', 'pymongo'],
'text': 'My first blog post!'}
>>> posts.find_one({"author": "Eliot"})
>>> post_id
ObjectId('5ba70fb1c9bb161d3c03bb4a')
>>> pprint.pprint(posts.find_one({"_id": post_id}))
{'_id': ObjectId('5ba70fb1c9bb161d3c03bb4a'),
'author': 'Mike',
'date': datetime.datetime(2018, 9, 23, 3, 58, 27, 70000),
'tags': ['mongodb', 'python', 'pymongo'],
'text': 'My first blog post!'}
>>> post_id_as_str = str(post_id)
>>> posts.find_one({"_id": post_id_as_str})
>>> quit()
おわりに
PythonからMongoDBにアクセスできるように、pymongoをインストールしました。
参考情報
関連記事
参考書籍(Amazon)
