0
1

More than 3 years have passed since last update.

MongoDBをpymongoで操作してみる

Posted at

はじめに

最近、mongoDBを触る機会が多いので、pythonと組み合わせて処理させてみました。

DBに接続

まずはpymongoをインポートしよう

from pymongo import MongoClient

続いて、データベースに接続する。
この例では、localhostのポート番号27017に接続し、
testというデータベースにつないだ上で
id/passで認証を行い、
bookという名前のコレクションに接続している。

client = MongoClient('localhost', 27017)
database = client['test']
database.authenticate("id", "apass")
collection = database['book']

データ抽出(select/find)

基本形

フィルタ条件なしでコレクションの全データを取ってくるスタイル

filter = {}
collection.find(filter=filter)

単純なフィルタ

フィールドの値が等しいものだけを検索
下記の例ではフィールド名starがvalue2であるレコードを抽出しています。

filter = {'star': 'value2'}
collection.find(filter=filter)

否定のフィルタ

star属性がvalue2では無いレコードを検索する

filter = {'star': {$ne: "value2"}}
collection.find(filter=filter)

フィールドの存在有無に起因するフィルタ

フィールドの値の存在有無を検索する。下記の例ではbirth属性が存在するレコードを検索している。

filter = {"birth": {"$exists": True}}
collection.find(filter=filter)

複数条件の複合検索

フィールドの値の存在有無を検索する。下記の例ではbirth属性が2005 かつ name属性が testaccであるレコードを検索している。

filter = {$and: [{'birth': '2005'},{"name": 'testacc'}]}
collection.find(filter=filter)

0
1
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
0
1