sql >> データベース >  >> NoSQL >> MongoDB

PythonとMongoDB:NoSQLデータベースへの接続

    MongoDBは、ドキュメント指向のNoSQLデータベースソリューションであり、強力なクエリシステムとともに優れたスケーラビリティと柔軟性を提供します。 MongoDBとPythonを使用すると、さまざまな種類のデータベースアプリケーションをすばやく開発できます。したがって、Pythonアプリケーションに言語自体と同じくらい柔軟なデータベースが必要な場合は、MongoDBが最適です。

    このチュートリアルでは、次のことを学びます。

    • MongoDB
    • インストールして実行する方法 MongoDB
    • MongoDBデータベースの操作方法
    • 低レベルのPyMongoドライバーの使用方法 MongoDBとのインターフェースに
    • 高レベルのMongoEngineオブジェクトドキュメントマッパー(ODM)の使用方法

    このチュートリアル全体を通して、MongoDBの柔軟性とパワーおよびその優れたPythonサポートを示すいくつかの例を記述します。これらの例のソースコードをダウンロードするには、以下のリンクをクリックしてください。

    ソースコードを取得する: このチュートリアルでPythonでMongoDBを使用する方法を学ぶために使用するソースコードを入手するには、ここをクリックしてください。


    SQLデータベースとNoSQLデータベースの使用

    何十年もの間、SQLデータベースは、大規模でスケーラブルなデータベースシステムの構築を検討している開発者にとって唯一の選択肢の1つでした。ただし、複雑なデータ構造を保存する必要性が高まったことで、 NoSQLが誕生しました。 データベース。この新しい種類のデータベースシステムにより、開発者は異種の構造のないデータを効率的に保存できます。

    一般に、NoSQLデータベースシステムは、SQLリレーショナルデータベース管理システム(RDBMS)とは大きく異なる方法でデータを保存および取得します。

    現在利用可能なデータベーステクノロジから選択する場合、SQLシステムとNoSQLシステムのどちらを使用するかを決定する必要がある場合があります。どちらにも、どちらかを選択するときに考慮する必要のある特定の機能があります。それらのより実質的な違いのいくつかを次に示します。

    プロパティ SQLデータベース NoSQLデータベース
    データモデル リレーショナル 非リレーショナル
    構造 テーブルベース、列と行あり ドキュメントベース、キーと値のペア、グラフ、またはワイド列
    スキーマ すべてのレコード(行)が同じ性質であり、同じプロパティを所有する、事前定義された厳密なスキーマ 動的スキーマまたはスキーマレス。これは、レコードが同じ性質である必要がないことを意味します
    クエリ言語 構造化照会言語(SQL) データベースによって異なります
    スケーラビリティ 垂直 水平
    ACIDトランザクション サポート 特定のNoSQLデータベースに応じてサポートされます
    新しいプロパティを追加する機能 最初にスキーマを変更する必要があります 何も邪魔することなく可能

    2種類のデータベースには他にも多くの違いがありますが、上記のデータベースは知っておくべき重要なもののいくつかです。

    データベースを選択するときは、その長所と短所を慎重に検討する必要があります。また、データベースが特定のシナリオとアプリケーションの要件にどのように適合するかを考慮する必要があります。適切な解決策は、SQLデータベースとNoSQLデータベースの組み合わせを使用して、より広範なシステムのさまざまな側面を処理することです。

    SQLデータベースの一般的な例は次のとおりです。

    • SQLite
    • MySQL
    • Oracle
    • PostgreSQL
    • Microsoft SQL Server

    NoSQLデータベースの例は次のとおりです。

    • DynamoDB
    • カサンドラ
    • Redis
    • CouchDB
    • RethinkDB
    • RavenDB
    • MongoDB

    近年、SQLデータベースとNoSQLデータベースの統合も始まって​​います。たとえば、PostgreSQL、MySQL、Microsoft SQL Serverなどのデータベースシステムは、NoSQLデータベースと同様に、JSONデータの保存とクエリをサポートするようになりました。これにより、両方のテクノロジーで同じ結果の多くを達成できるようになりました。ただし、水平方向のスケーリングやユーザーフレンドリーなインターフェースなど、NoSQLの機能の多くはまだ利用できません。

    SQLおよびNoSQLデータベースに関するこの簡単な背景を使用して、このチュートリアルのメイントピックであるMongoDBデータベースに集中できます。 Pythonでの使用方法。



    MongoDBを使用したNoSQLデータベースの管理

    MongoDBはドキュメント指向です NoSQLとして分類されたデータベース。近年、業界全体で人気があり、Pythonと非常によく統合されています。従来のSQLRDBMSとは異なり、MongoDBはコレクションを使用します ドキュメントテーブルの代わりに の データを整理して保存します。

    MongoDBは、スキーマレスで柔軟なJSONのようなドキュメントにデータを格納します。ここでは、スキーマレス つまり、厳密なテーブルスキーマを満たす必要なしに、同じコレクション内に異なるフィールドのセットを持つドキュメントを作成できます。 。

    ドキュメントとデータの構造を時間の経過とともに変更できるため、複雑なデータ移行プロセスを必要とせずに、要件の変更に迅速に適応できる柔軟なシステムが実現します。ただし、新しいドキュメントの構造を変更する際のトレードオフは、既存のドキュメントが更新されたスキーマと矛盾するようになることです。したがって、これは注意して管理する必要があるトピックです。

    注: JSONはJavaScriptObject Notationの略です 。これは、任意の深さでネストできるキーと値のペアで構成される、人間が読める形式のファイル形式です。

    MongoDBはC++で記述されており、MongoDB Incによって積極的に開発されています。これは、macOS、Windows、Solaris、およびほとんどのLinuxディストリビューションなどのすべての主要なプラットフォームで実行されます。一般に、MongoDBデータベースの背後にある3つの主要な開発目標があります。

    1. 適切にスケーリング
    2. 豊富なデータ構造を保存する
    3. 高度なクエリメカニズムを提供する

    MongoDBは分散型です データベースであるため、高可用性、水平スケーリング、および地理的分散がシステムに組み込まれています。柔軟なJSONのようなドキュメントにデータを保存します。これらのドキュメントをモデル化して、アプリケーション内のオブジェクトをマッピングできます。これにより、データを効果的に操作できます。

    MongoDBは、アドホッククエリ、インデックス作成、集計、地理空間検索、テキスト検索などをサポートする強力なクエリ言語を提供します。これにより、データにアクセスして操作するための強力なツールキットが提供されます。最後に、MongoDBは無料で利用でき、優れたPythonサポートを備えています。


    MongoDBの機能の確認

    これまで、MongoDBとは何か、そしてその主な目標は何かを学びました。このセクションでは、MongoDBのより重要な機能のいくつかについて学習します。データベース管理側に関しては、MongoDBは次の機能を提供します。

    • クエリのサポート: マッチング( ==)など、多くの標準クエリタイプを使用できます )、比較( <> )、および正規表現。
    • データの調整: 構造化、部分構造化、さらには多態性など、事実上あらゆる種類のデータを保存できます。
    • スケーラビリティ: サーバークラスターにマシンを追加するだけで、より多くのクエリを処理できます。
    • 柔軟性と敏捷性: これを使用してアプリケーションをすばやく開発できます。
    • ドキュメントの向きとスキーマレス: データモデルに関するすべての情報を1つのドキュメントに保存できます。
    • 調整可能なスキーマ: データベースのスキーマをその場で変更できるため、新しい機能を提供したり、既存の問題を修正したりするために必要な時間が短縮されます。
    • リレーショナルデータベースの機能: インデックス作成など、リレーショナルデータベースに共通のアクションを実行できます。

    運用面に関しては、MongoDBは、他のデータベースシステムにはないいくつかのツールと機能を提供します。

    • スケーラビリティ: スタンドアロンサーバーが必要な場合でも、独立したサーバーの完全なクラスターが必要な場合でも、MongoDBを必要なサイズに拡張できます。
    • 負荷分散のサポート: MongoDBは、さまざまなシャード間でデータを自動的に移動します。
    • 自動フェイルオーバーのサポート: プライマリサーバーがダウンすると、新しいプライマリが自動的に稼働します。
    • 管理ツール: クラウドベースのMongoDBManagementService(MMS)を使用してマシンを追跡できます。
    • メモリ効率: メモリマップトファイルのおかげで、MongoDBはリレーショナルデータベースよりも効率的であることがよくあります。

    これらの機能はすべて非常に便利です。たとえば、インデックス機能を利用すると、データの多くがメモリに保持され、すばやく取得できます。特定のドキュメントキーにインデックスを付けなくても、MongoDBは最も最近使用されていない手法を使用してかなりの量のデータをキャッシュします。



    MongoDBのインストールと実行

    MongoDBに慣れてきたので、手を汚して使い始めましょう。ただし、最初に、マシンにインストールする必要があります。 MongoDBの公式サイトでは、データベースサーバーの2つのエディションが提供されています。

    1. Community Editionは、アドホッククエリ、インデックス作成、リアルタイム集計とともに柔軟なドキュメントモデルを提供し、データにアクセスして分析するための強力な方法を提供します。このエディションは無料で入手できます。
    2. Enterprise Editionは、Community Editionと同じ機能に加えて、セキュリティと監視に関連するその他の高度な機能を提供します。これは商用版ですが、評価と開発の目的で無制限に無料で使用できます。

    Windowsを使用している場合は、インストールチュートリアルを読んで、完全な手順を確認できます。通常、ダウンロードページに移動し、[利用可能なダウンロード]ボックスでWindowsプラットフォームを選択し、 .msiを選択します。 現在のシステムに適合するインストーラーを選択し、[ダウンロード]をクリックします 。

    インストーラーを実行し、インストールウィザードの画面の指示に従います。このページでは、MongoDBをWindowsサービスとして実行する方法についても説明しています。

    macOSを使用している場合は、Homebrewを使用してシステムにMongoDBをインストールできます。完全なガイドを入手するには、インストールチュートリアルを参照してください。また、MongoDBをmacOSサービスとして実行するための指示に必ず従ってください。

    Linuxを使用している場合、インストールプロセスは特定のディストリビューションによって異なります。さまざまなLinuxシステムにMongoDBをインストールする方法の詳細なガイドについては、インストールチュートリアルページに移動し、現在のオペレーティングシステムに一致するチュートリアルを選択してください。必ずMongoDBデーモンmongodを実行してください 、インストールの最後に。

    最後に、Dockerを使用してMongoDBをインストールすることもできます。これは、システムを別のインストールで乱雑にしたくない場合に便利です。このインストールオプションをご希望の場合は、公式チュートリアルを読み、その指示に従うことができます。この場合、Dockerの使用方法に関する予備知識が必要になることに注意してください。

    システムにMongoDBデータベースをインストールして実行すると、 mongoを使用して実際のデータベースでの作業を開始できます。 シェル。




    mongoを使用したMongoDBデータベースの作成 シェル

    インストールと実行の手順に従っている場合は、システムでMongoDBのインスタンスがすでに実行されているはずです。これで、独自のデータベースの作成とテストを開始できます。このセクションでは、 mongoの使用方法を学習します データベース上のドキュメントを作成、読み取り、更新、削除するためのシェル。


    mongoの実行 シェル

    mongo shellは、MongoDBへのインタラクティブなJavaScriptインターフェースです。このツールを使用して、データのクエリと操作、および管理操作を実行できます。これはJavaScriptインターフェースであるため、使い慣れたSQL言語を使用してデータベースをクエリすることはありません。代わりに、JavaScriptコードを使用します。

    mongoを起動するには シェルで、ターミナルまたはコマンドラインを開き、次のコマンドを実行します。

    $ mongo
    

    このコマンドを使用すると、 mongoに移動します。 シェル。この時点で、シェルのバージョンとサーバーのアドレスとポートに関する情報を含む一連のメッセージが表示される可能性があります。最後に、シェルプロンプト(> )が表示されます )クエリとコマンドを入力します。

    データベースアドレスを引数としてmongoに渡すことができます 指図。リモートデータベースにアクセスするためのホストとポートを指定するなど、いくつかのオプションを使用することもできます。 mongoの使用方法の詳細については コマンドを実行すると、 mongo --helpを実行できます。 。



    接続の確立

    mongoを実行するとき 引数なしのコマンドは、シェルを起動し、 mongodによって提供されるデフォルトのローカルサーバーに接続します mongod://127.0.0.1:27017で処理 。これは、ポート 27017を介してローカルホストに接続していることを意味します 。

    デフォルトでは、 mongo シェルは、 testへの接続を確立することでセッションを開始します データベース。 dbを介して現在のデータベースにアクセスできます オブジェクト:

    > db
    test
    >
    

    この場合、 db testへの参照を保持します 、これはデフォルトのデータベースです。データベースを切り替えるには、コマンド useを発行します 、引数としてデータベース名を指定します。

    たとえば、Pythonコンテンツを公開するWebサイトを作成し、MongoDBを使用してチュートリアルと記事を保存することを計画しているとします。その場合、次のコマンドを使用してサイトのデータベースに切り替えることができます。

    > use rptutorials
    switched to db rptutorials
    

    このコマンドは、接続を rptutorialsに切り替えます データベース。 MongoDBは、実際のデータをデータベースに挿入するまで、ファイルシステム上に物理データベースファイルを作成しません。したがって、この場合、 rptutorials 現在のデータベースリストには表示されません:

    > show dbs
    admin          0.000GB
    config         0.000GB
    local          0.000GB
    >
    

    mongo シェルは多くの機能とオプションを提供します。データのクエリと操作、およびデータベースサーバー自体の管理が可能になります。

    SQLなどの標準化されたクエリ言語を使用する代わりに、 mongo シェルはJavaScriptプログラミング言語とユーザーフレンドリーなAPIを使用しています。このAPIを使用すると、次のセクションのトピックであるデータを試すことができます。



    コレクションとドキュメントの作成

    MongoDBデータベースは、ドキュメントのコレクションの物理コンテナーです。各データベースは、ファイルシステム上で独自のファイルセットを取得します。これらのファイルは、複数のデータベースを処理できるMongoDBサーバーによって管理されます。

    MongoDBでは、コレクション ドキュメントのグループです 。コレクションは、従来のRDBMSのテーブルにいくぶん似ていますが、厳密なスキーマを課すことはありません。理論的には、コレクション内の各ドキュメントは、完全に異なる構造またはフィールドのセットを持つことができます。

    実際には、コレクション内のドキュメントは通常、同様の構造を共有して、均一な取得、挿入、および更新プロセスを可能にします。更新および挿入時にドキュメント検証ルールを使用することで、統一されたドキュメント構造を適用できます。

    異なるドキュメント構造を許可することは、MongoDBコレクションの重要な機能です。この機能は柔軟性を提供し、正式なテーブルスキーマを変更することなくドキュメントに新しいフィールドを追加できるようにします。

    mongoを使用してコレクションを作成するには シェル、 dbを指す必要があります ターゲットデータベースに移動し、ドット表記を使用してコレクションを作成します :

    > use rptutorials
    switched to db rptutorials
    > db
    rptutorials
    > db.tutorial
    rptutorials.tutorial
    

    この例では、ドット表記を使用して tutorialを作成します rptutorialsのコレクションとして 、これは現在のデータベースです。 MongoDBはデータベースとコレクションを怠惰に作成することに注意することが重要です。 。つまり、最初のドキュメントを挿入した後にのみ物理的に作成されます。

    データベースとコレクションができたら、ドキュメントの挿入を開始できます。ドキュメントは、MongoDBのストレージの単位です。 RDBMSでは、これはテーブル行に相当します。ただし、MongoDBのドキュメントは、配列、埋め込みドキュメント、さらにはドキュメントの配列などの複雑な情報を格納できるため、行よりもはるかに用途が広いです。

    MongoDBは、ドキュメントをバイナリJSONと呼ばれる形式で保存します (BSON)、これはJSONのバイナリ表現です。 MongoDBのドキュメントは、フィールドと値のペアで構成されており、次の構造になっています。

    {
       field1 → value1,
       field2 → value2,
       field3 → value3,
       ...
       fieldN → valueN
    }
    

    フィールドの値は、他のドキュメント、配列、ドキュメントの配列など、任意のBSONデータ型にすることができます。実際には、JSON形式を使用してドキュメントを指定します。

    MongoDBデータベースアプリケーションを構築する場合、おそらく最も重要な決定はドキュメントの構造に関するものです。つまり、ドキュメントに含めるフィールドと値を決定する必要があります。

    Pythonサイトのチュートリアルの場合、ドキュメントは次のように構成されている可能性があります。

    {
        "title": "Reading and Writing CSV Files in Python",
        "author": "Jon",
        "contributors": [
            "Aldren",
            "Geir Arne",
            "Joanna",
            "Jason"
        ],
        "url": "https://realpython.com/python-csv/"
    }
    

    ドキュメントは、基本的にプロパティ名とその値のセットです。値は、文字列や数値などの単純なデータ型にすることができますが、 Contributorsなどの配列にすることもできます。 上記の例では。

    MongoDBのドキュメント指向データモデルは、当然、複雑なデータを単一のオブジェクトとして表します。これにより、複数の場所やテーブルを確認しなくても、データオブジェクトを全体的に操作できます。

    従来のRDBMSを使用してチュートリアルを保存している場合は、チュートリアルを保存するためのテーブルと、寄稿者を保存するための別のテーブルがあります。次に、後でデータを取得できるように、両方のテーブル間に関係を設定する必要があります。



    コレクションとドキュメントの操作

    これまでのところ、 mongoの実行方法と使用方法の基本を理解しています。 シェル。また、JSON形式を使用して独自のドキュメントを作成する方法も知っています。次に、MongoDBデータベースにドキュメントを挿入する方法を学びます。

    mongoを使用してデータベースにドキュメントを挿入するには シェルでは、最初にコレクションを選択してから、 .insertOne()を呼び出す必要があります ドキュメントを引数としてコレクションに:

    > use rptutorials
    switched to db rptutorials
    
    > db.tutorial.insertOne({
    ...     "title": "Reading and Writing CSV Files in Python",
    ...     "author": "Jon",
    ...     "contributors": [
    ...         "Aldren",
    ...         "Geir Arne",
    ...         "Joanna",
    ...         "Jason"
    ...     ],
    ...     "url": "https://realpython.com/python-csv/"
    ... })
    {
        "acknowledged" : true,
        "insertedId" : ObjectId("600747355e6ea8d224f754ba")
    }
    

    最初のコマンドで、使用するデータベースに切り替えます。 2番目のコマンドは、選択したコレクション tutorialに単純なドキュメントを挿入するJavaScriptメソッド呼び出しです。 。 入力を押したら 、画面に、新しく挿入されたドキュメントとその insertedIdについて通知するメッセージが表示されます。 。

    リレーショナルデータベースがテーブル内のすべての行を一意に識別するために主キーを必要とするのと同様に、MongoDBドキュメントには _idが必要です。 ドキュメントを一意に識別するフィールド。 MongoDBでは、カスタムの _idを入力できます あなたがその独自性を保証する限り。ただし、広く受け入れられている方法は、MongoDBが自動的に _idを挿入できるようにすることです。 あなたのために。

    同様に、 .insertMany()を使用して、一度に複数のドキュメントを追加できます。 :

    > tutorial1 = {
    ...     "title": "How to Iterate Through a Dictionary in Python",
    ...     "author": "Leodanis",
    ...     "contributors": [
    ...         "Aldren",
    ...         "Jim",
    ...         "Joanna"
    ...     ],
    ...     "url": "https://realpython.com/iterate-through-dictionary-python/"
    ... }
    
    > tutorial2 = {
    ...      "title": "Python 3's f-Strings: An Improved String Formatting Syntax",
    ...      "author": "Joanna",
    ...      "contributors": [
    ...          "Adriana",
    ...          "David",
    ...          "Dan",
    ...          "Jim",
    ...          "Pavel"
    ...      ],
    ...      "url": "https://realpython.com/python-f-strings/"
    ... }
    
    > db.tutorial.insertMany([tutorial1, tutorial2])
    {
        "acknowledged" : true,
        "insertedIds" : [
            ObjectId("60074ff05e6ea8d224f754bb"),
            ObjectId("60074ff05e6ea8d224f754bc")
        ]
    }
    

    ここでは、 .insertMany()の呼び出し チュートリアルのリストを取得し、データベースに挿入します。この場合も、シェル出力には、新しく挿入されたドキュメントと自動的に追加された _idに関する情報が表示されます。 フィールド。

    mongo shellは、データベースに対して読み取り、更新、および削除操作を実行するためのメソッドも提供します。たとえば、 .find()を使用できます コレクション内のドキュメントを取得するには:

    > db.tutorial.find()
    { "_id" : ObjectId("600747355e6ea8d224f754ba"),
    "title" : "Reading and Writing CSV Files in Python",
    "author" : "Jon",
    "contributors" : [ "Aldren", "Geir Arne", "Joanna", "Jason" ],
    "url" : "https://realpython.com/python-csv/" }
        ...
    
    > db.tutorial.find({author: "Joanna"})
    { "_id" : ObjectId("60074ff05e6ea8d224f754bc"),
    "title" : "Python 3's f-Strings: An Improved String Formatting Syntax (Guide)",
    "author" : "Joanna",
    "contributors" : [ "Adriana", "David", "Dan", "Jim", "Pavel" ],
    "url" : "https://realpython.com/python-f-strings/" }
    

    .find()への最初の呼び出し tutorial内のすべてのドキュメントを取得します コレクション。一方、 .find()への2回目の呼び出し Joannaによって作成されたチュートリアルを取得します。

    mongoを介してMongoDBを使用する方法に関するこの背景知識 シェル、PythonでMongoDBの使用を開始する準備が整いました。次のいくつかのセクションでは、PythonアプリケーションでMongoDBデータベースを使用するためのさまざまなオプションについて説明します。




    PythonおよびPyMongoでのMongoDBの使用

    これで、MongoDBとは何か、および mongoを使用してデータベースを作成および管理する方法がわかりました。 シェルでは、MongoDBの使用を開始できますが、今回はPythonを使用します。 MongoDBは、PyMongoと呼ばれる公式のPythonドライバーを提供します。

    このセクションでは、PyMongoを使用してMongoDBとPythonを使用して独自のデータベースアプリケーションを作成する方法を理解するのに役立ついくつかの例を紹介します。

    PyMongo内の各モジュールは、データベースに対する一連の操作を担当します。少なくとも次のタスク用のモジュールがあります:

    • データベース接続の確立
    • データベースの操作
    • コレクションとドキュメントの操作
    • カーソルの操作
    • データ暗号化の操作

    一般に、PyMongoは、MongoDBサーバーとの通信に使用できる豊富なツールセットを提供します。クエリ、結果の取得、データの書き込みと削除、データベースコマンドの実行を行う機能を提供します。


    PyMongoのインストール

    PyMongoの使用を開始するには、まずPython環境にPyMongoをインストールする必要があります。仮想環境を使用することも、システム全体のPythonインストールを使用することもできますが、最初のオプションが推奨されます。 PyMongoはPyPIで利用できるため、インストールする最も簡単な方法は pipを使用することです。 。ターミナルを起動し、次のコマンドを実行します:

    $ pip install pymongo==3.11.2
    

    いくつかのダウンロードとその他の関連手順の後、このコマンドはPython環境にPyMongoをインストールします。特定のバージョン番号を指定しない場合は、 pip 利用可能な最新バージョンをインストールします。

    注: PyMongoのインストール方法の完全なガイドについては、公式ドキュメントのインストール/アップグレードページをご覧ください。

    インストールが完了したら、Pythonインタラクティブセッションを開始して、次のインポートを実行できます。

    >>>
    >>> import pymongo
    

    Pythonシェルで例外を発生させずにこれを実行すると、インストールは正常に機能します。そうでない場合は、手順をもう一度慎重に実行してください。



    接続の確立

    データベースへの接続を確立するには、 MongoClientを作成する必要があります 実例。このクラスは、MongoDBインスタンスまたはサーバーのクライアントを提供します。各クライアントオブジェクトには組み込みの接続プールがあり、デフォルトでサーバーへの最大100の接続を処理します。

    Pythonインタラクティブセッションに戻り、 MongoClientをインポートします pymongoから 。次に、現在実行中のMongoDBインスタンスと通信するクライアントオブジェクトを作成します。

    >>>
    >>> from pymongo import MongoClient
    >>> client = MongoClient()
    >>> client
    MongoClient(host=['localhost:27017'], ..., connect=True)
    

    上記のコードは、デフォルトのホスト( localhost )への接続を確立します )およびポート( 27017 )。 MongoClient カスタムホスト、ポート、およびその他の接続パラメーターを指定できるようにする一連の引数を取ります。たとえば、カスタムホストとポートを提供するには、次のコードを使用できます。

    >>>
    >>> client = MongoClient(host="localhost", port=27017)
    

    これは、 hostを提供する必要がある場合に便利です。 およびport これはMongoDBのデフォルト設定とは異なります。 MongoDB URI形式を使用することもできます:

    >>>
    >>> client = MongoClient("mongodb://localhost:27017")
    

    MongoClientのこれらすべてのインスタンス 現在のMongoDBインスタンスに接続するために同じクライアントセットアップを提供します。どちらを使用するかは、コードでどの程度明示的にしたいかによって異なります。

    MongoClientをインスタンス化したら 、 mongo で行ったように、そのインスタンスを使用してその特定のデータベース接続を参照できます。 シェルのdb 上記のセクションのオブジェクト。



    データベース、コレクション、およびドキュメントの操作

    MongoClientのインスタンスを接続したら 、指定されたMongoDBサーバーによって管理されている任意のデータベースにアクセスできます。使用するデータベースを定義するには、 mongoで行ったのと同じようにドット表記を使用できます。 シェル:

    >>>
    >>> db = client.rptutorials
    >>> db
    Database(MongoClient(host=['localhost:27017'], ..., connect=True), 'rptutorials')
    

    この場合、 rptutorials 使用するデータベースの名前です。データベースが存在しない場合は、MongoDBがデータベースを作成しますが、データベースに対して最初の操作を実行した場合に限ります。

    データベースの名前が有効なPython識別子でない場合は、辞書形式のアクセスを使用することもできます。

    >>>
    >>> db = client["rptutorials"]
    

    このステートメントは、データベースの名前が有効なPython識別子ではない場合に便利です。たとえば、データベースの名前が rp-tutorialsの場合 、次に辞書形式のアクセスを使用する必要があります。

    注: mongoを使用する場合 シェルの場合、 dbを介してデータベースにアクセスできます グローバルオブジェクト。 PyMongoを使用する場合、データベースを dbという変数に割り当てることができます。 同様の動作をするために。

    PyMongoを使用してデータベースにデータを保存することは、 mongoで行ったのと似ています。 上記のセクションのシェル。ただし、最初に、ドキュメントを作成する必要があります。 Pythonでは、辞書を使用してドキュメントを作成します。

    >>>
    >>> tutorial1 = {
    ...     "title": "Working With JSON Data in Python",
    ...     "author": "Lucas",
    ...     "contributors": [
    ...         "Aldren",
    ...         "Dan",
    ...         "Joanna"
    ...     ],
    ...     "url": "https://realpython.com/python-json/"
    ... }
    

    ドキュメントを辞書として作成したら、使用するコレクションを指定する必要があります。これを行うには、データベースオブジェクトでドット表記を使用できます。

    >>>
    >>> tutorial = db.tutorial
    >>> tutorial
    Collection(Database(..., connect=True), 'rptutorials'), 'tutorial')
    

    この場合、 tutorial Collectionのインスタンスです データベース内のドキュメントの物理的なコレクションを表します。 tutorialにドキュメントを挿入できます .insert_one()を呼び出す 引数としてドキュメントを使用して:

    >>>
    >>> result = tutorial.insert_one(tutorial1)
    >>> result
    <pymongo.results.InsertOneResult object at 0x7fa854f506c0>
    
    >>> print(f"One tutorial: {result.inserted_id}")
    One tutorial: 60084b7d87eb0fbf73dbf71d
    

    ここでは、 .insert_one() tutorial1を取ります 、 tutorialに挿入します コレクションを返し、 InsertOneResultを返します 物体。このオブジェクトは、挿入されたドキュメントに関するフィードバックを提供します。 MongoDBはObjectIdを生成するため、注意してください 動的に、出力は ObjectIdと一致しません 上に表示されています。

    データベースに追加するドキュメントが多数ある場合は、 .insert_many()を使用できます。 それらを一度に挿入するには:

    >>>
    >>> tutorial2 = {
    ...     "title": "Python's Requests Library (Guide)",
    ...     "author": "Alex",
    ...     "contributors": [
    ...         "Aldren",
    ...         "Brad",
    ...         "Joanna"
    ...     ],
    ...     "url": "https://realpython.com/python-requests/"
    ... }
    
    >>> tutorial3 = {
    ...     "title": "Object-Oriented Programming (OOP) in Python 3",
    ...     "author": "David",
    ...     "contributors": [
    ...         "Aldren",
    ...         "Joanna",
    ...         "Jacob"
    ...     ],
    ...     "url": "https://realpython.com/python3-object-oriented-programming/"
    ... }
    
    >>> new_result = tutorial.insert_many([tutorial2, tutorial3])
    
    >>> print(f"Multiple tutorials: {new_result.inserted_ids}")
    Multiple tutorials: [
       ObjectId('6008511c87eb0fbf73dbf71e'),
       ObjectId('6008511c87eb0fbf73dbf71f')
    ]
    

    これは、 .insert_one()を呼び出すよりも高速で簡単です。 複数回。 .insert_many()の呼び出し 反復可能なドキュメントを取得し、それらを tutorialに挿入します rptutorialsのコレクション データベース。このメソッドは、 InsertManyResultのインスタンスを返します。 、挿入されたドキュメントに関する情報を提供します。

    コレクションからドキュメントを取得するには、 .find()を使用できます 。引数がない場合、 .find() カーソルを返します コレクション内のドキュメントをオンデマンドで生成するオブジェクト:

    >>>
    >>> import pprint
    
    >>> for doc in tutorial.find():
    ...     pprint.pprint(doc)
    ...
    {'_id': ObjectId('600747355e6ea8d224f754ba'),
     'author': 'Jon',
     'contributors': ['Aldren', 'Geir Arne', 'Joanna', 'Jason'],
     'title': 'Reading and Writing CSV Files in Python',
     'url': 'https://realpython.com/python-csv/'}
        ...
    {'_id': ObjectId('6008511c87eb0fbf73dbf71f'),
     'author': 'David',
     'contributors': ['Aldren', 'Joanna', 'Jacob'],
     'title': 'Object-Oriented Programming (OOP) in Python 3',
     'url': 'https://realpython.com/python3-object-oriented-programming/'}
    

    Here, you run a loop on the object that .find() returns and print successive results, using pprint.pprint() to provide a user-friendly output format.

    You can also use .find_one() to retrieve a single document. In this case, you can use a dictionary that contains fields to match. For example, if you want to retrieve the first tutorial by Jon, then you can do something like this:

    >>>
    >>> import pprint
    
    >>> jon_tutorial = tutorial.find_one({"author": "Jon"})
    
    >>> pprint.pprint(jon_tutorial)
    {'_id': ObjectId('600747355e6ea8d224f754ba'),
     'author': 'Jon',
     'contributors': ['Aldren', 'Geir Arne', 'Joanna', 'Jason'],
     'title': 'Reading and Writing CSV Files in Python',
     'url': 'https://realpython.com/python-csv/'}
    

    Note that the tutorial’s ObjectId is set under the _id key, which is the unique document identifier that MongoDB automatically adds when you insert a document into your database.

    PyMongo also provides methods to replace, update, and delete documents from a database. If you want to dive deeper into these features, then take a look at the documentation for Collection



    Closing Connections

    Establishing a connection to a MongoDB database is typically an expensive operation. If you have an application that constantly retrieves and manipulates data in a MongoDB database, then you probably don’t want to be opening and closing the connection all the time since this might affect your application’s performance.

    In this kind of situation, you should keep your connection alive and only close it before exiting the application to clear all the acquired resources. You can close the connection by calling .close() on the MongoClient instance:

    >>>
    >>> client.close()
    

    Another situation is when you have an application that occasionally uses a MongoDB database. In this case, you might want to open the connection when needed and close it immediately after use for freeing the acquired resources. A consistent approach to this problem would be to use the with 声明。 Yes, MongoClient implements the context manager protocol:

    >>>
    >>> import pprint
    >>> from pymongo import MongoClient
    
    >>> with MongoClient() as client:
    ...     db = client.rptutorials
    ...     for doc in db.tutorial.find():
    ...         pprint.pprint(doc)
    ...
    {'_id': ObjectId('600747355e6ea8d224f754ba'),
     'author': 'Jon',
     'contributors': ['Aldren', 'Geir Arne', 'Joanna', 'Jason'],
     'title': 'Reading and Writing CSV Files in Python',
     'url': 'https://realpython.com/python-csv/'}
        ...
    {'_id': ObjectId('6008511c87eb0fbf73dbf71f'),
     'author': 'David',
     'contributors': ['Aldren', 'Joanna', 'Jacob'],
     'title': 'Object-Oriented Programming (OOP) in Python 3',
     'url': 'https://realpython.com/python3-object-oriented-programming/'}
    

    If you use the with statement to handle your MongoDB client, then at the end of the with code block, the client’s .__exit__() method gets called, which at the same time closes the connection by calling .close()




    Using MongoDB With Python and MongoEngine

    While PyMongo is a great and powerful Python driver for interfacing with MongoDB, it’s probably a bit too low-level for many of your projects. With PyMongo, you’ll have to write a lot of code to consistently insert, retrieve, update, and delete documents.

    One library that provides a higher abstraction on top of PyMongo is MongoEngine. MongoEngine is an object-document mapper (ODM), which is roughly equivalent to an SQL-based object-relational mapper (ORM). MongoEngine provides a class-based abstraction, so all the models you create are classes.


    Installing MongoEngine

    There are a handful of Python libraries to help you work with MongoDB. MongoEngine, however, is a popular one that provides a nice set of features, flexibility, and community support. MongoEngine is available on PyPI. You can install it using the following pip コマンド:

    $ pip install mongoengine==0.22.1
    

    Once you’ve installed MongoEngine into your Python environment, you’re ready to start working with MongoDB databases using Python’s object-oriented features. The next step is to connect to your running MongoDB instance.



    Establishing a Connection

    To establish a connection with your database, you need to use mongoengine.connect() 。 This function takes several arguments. However, in this tutorial, you’ll use only three of them. Within your Python interactive session, type the following code:

    >>>
    >>> from mongoengine import connect
    >>> connect(db="rptutorials", host="localhost", port=27017)
    MongoClient(host=['localhost:27017'], ..., read_preference=Primary())
    

    Here, you first set the database name db to "rptutorials" , which is the name of the database you want to work in. Then you provide a host and a port to connect to your current MongoDB instance. Since you’re using the default host and port , you can omit these two parameters and just use connect("rptutorials")



    Working With Collections and Documents

    To create documents with MongoEngine, you first need to define what data you want the documents to have. In other words, you need to define a document schema. MongoEngine encourages you to define a document schema to help you reduce coding errors and to allow you to define utility or helper methods.

    Similar to ORMs, ODMs like MongoEngine provide a base or model class for you to define a document schema. In ORMs, that class is equivalent to a table, and its instances are equivalent to rows. In MongoEngine, the class is equivalent to a collection, and its instances are equivalent to documents.

    To create a model, you need to subclass Document and provide the required fields as class attributes. To continue with the blog example, here’s how you can create a model for your tutorials:

    >>>
    >>> from mongoengine import Document, ListField, StringField, URLField
    
    >>> class Tutorial(Document):
    ...     title = StringField(required=True, max_length=70)
    ...     author = StringField(required=True, max_length=20)
    ...     contributors = ListField(StringField(max_length=20))
    ...     url = URLField(required=True)
    

    With this model, you tell MongoEngine that you expect a Tutorial document to have a .title , an .author , a list of .contributors , and a .url 。 The base class, Document , uses that information along with the field types to validate the input data for you.

    Note: One of the more difficult tasks with database models is data validation 。 How do you make sure that the input data conforms to your format requirements? That’s one of the reasons for you to have a coherent and uniform document schema.

    MongoDB is said to be a schemaless database, but that doesn’t mean it’s schema free. Having documents with a different schema within the same collection can lead to processing errors and inconsistent behavior.

    For example, if you try to save a Tutorial object without a .title , then your model throws an exception and lets you know. You can take this even further and add more restrictions, such as the length of the .title , and so on.

    There are a few general parameters that you can use to validate fields. Here are some of the more commonly used parameters:

    • db_field specifies a different field name.
    • required ensures that the field is provided.
    • default provides a default value for a given field if no value is given.
    • unique ensures that no other document in the collection has the same value for this field.

    Each specific field type also has its own set of parameters. You can check the documentation for a complete guide to the available field types.

    To save a document to your database, you need to call .save() on a document object. If the document already exists, then all the changes will be applied to the existing document. If the document doesn’t exist, then it’ll be created.

    Here’s an example of creating and saving a tutorial into your sample tutorials database:

    >>>
    >>> tutorial1 = Tutorial(
    ...     title="Beautiful Soup: Build a Web Scraper With Python",
    ...     author="Martin",
    ...     contributors=["Aldren", "Geir Arne", "Jaya", "Joanna", "Mike"],
    ...     url="https://realpython.com/beautiful-soup-web-scraper-python/"
    ... )
    
    >>> tutorial1.save()  # Insert the new tutorial
    <Tutorial: Tutorial object>
    

    By default, .save() inserts the new document into a collection named after the model class, Tutorial , except using lowercase letters. In this case, the collection name is tutorial , which matches the collection you’ve been using to save your tutorials.

    PyMongo performs data validation when you call .save() 。 This means that it checks the input data against the schema you declared in the Tutorial model class. If the input data violates the schema or any of its constraints, then you get an exception, and the data isn’t saved into the database.

    For example, here’s what happens if you try to save a tutorial without providing a .title

    >>>
    >>> tutorial2 = Tutorial()
    >>> tutorial2.author = "Alex"
    >>> tutorial2.contributors = ["Aldren", "Jon", "Joanna"]
    >>> tutorial2.url = "https://realpython.com/convert-python-string-to-int/"
    >>> tutorial2.save()
    Traceback (most recent call last):
      ...
    mongoengine.errors.ValidationError: ... (Field is required: ['title'])
    

    In this example, first note that you can also build a Tutorial object by assigning values to its attributes. Second, since you don’t provide a .title for the new tutorial, .save() raises a ValidationError telling you that the .title フィールドは必須項目です。 Having automatic data validation is a great feature that will save you some headaches.

    Each Document subclass has an .objects attribute that you can use to access the documents in the associated collection. For example, here’s how you can print the .title of all your current tutorials:

    >>>
    >>> for doc in Tutorial.objects:
    ...     print(doc.title)
    ...
    Reading and Writing CSV Files in Python
    How to Iterate Through a Dictionary in Python
    Python 3's f-Strings: An Improved String Formatting Syntax (Guide)
    Working With JSON Data in Python
    Python's Requests Library (Guide)
    Object-Oriented Programming (OOP) in Python 3
    Beautiful Soup: Build a Web Scraper With Python
    

    The for loop iterates over all your tutorials and prints their .title data to the screen. You can also use .objects to filter your documents. For example, say you want to retrieve the tutorials authored by Alex. In that case, you can do something like this:

    >>>
    >>> for doc in Tutorial.objects(author="Alex"):
    ...     print(doc.title)
    ...
    Python's Requests Library (Guide)
    

    MongoEngine is well suited to manage your MongoDB databases for just about any type of application. Its features make it ideal for creating efficient and scalable programs using a high-level approach. If you’re looking for more information about MongoEngine, be sure to check out its user guide.




    Conclusion

    If you need a robust, scalable, and flexible database solution, then MongoDB might be a good option for you. MongoDB is a mature and popular NoSQL database with great Python support. With a good understanding of how to access MongoDB with Python, you’ll be ready to create database applications that scale well and provide excellent performance.

    With MongoDB, you also have the benefit of a human-readable and highly-flexible data model, so you can adapt to requirement changes quickly.

    In this tutorial, you learned:

    • What MongoDB and NoSQL databases are
    • How to install and run MongoDB on your system
    • How to create and work with MongoDB databases
    • How to interface with MongoDB in Python using the PyMongo driver
    • How to use the MongoEngine object-document mapper to work with MongoDB

    The examples you coded in this tutorial are available for download. To get their source code, click the link below:

    Get the Source Code: Click here to get the source code you’ll use to learn about using MongoDB with Python in this tutorial.



    1. Mongoose/MongoDBでのマルチフィールドインデックスの作成

    2. 要素の正規表現配列を使用したMongoDBクエリ$in

    3. mongodbからpandasにデータをインポートする方法は?

    4. CDPプライベートクラウドベース7とCDH5の運用データベースのパフォーマンスの向上