LoginSignup
5
4

More than 5 years have passed since last update.

MacのPythonでMongoを操作してみる

Posted at

私の使っているMacはPythonのバージョンが2.7.10なので、以下の方法でバージョンを合わせてpymongoを入れる必要があります。

sudo pip install pymongo==2.7.2

コネクション取得

ローカルにあるMongoDBに接続し、hogeというDBがMongoDB上にある場合以下のように書いてコネクションを取得します。

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from pymongo import Connection

# mongodbのコネクションを取得
con = Connection('localhost', 27017)
db = con.hoge

コレクション取得

hoge_mstというコレクションがhogeというDBにある場合以下のようにしてコレクションを取得します。

col = db.hoge_mst

コレクションからデータの取得

1件のみ取得

print col.find_one()

全件取得

for item in col.find():
    print item

全件取得し必要な項目だけ使いたい


```python
for item in col.find():
    print item['key1']

検索条件を指定して取得したい


```python
for item in col.find({'itemID':2}):
    print item['key1']
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4