Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

私の使っている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']
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away