LoginSignup
1
0

More than 5 years have passed since last update.

MongoDBにデータを入れてみる

Last updated at Posted at 2015-02-22

やること

ひたすら"hogehoge"という文字列をローカルにたてたMongoDBにぶち込み続ける

じゅんび

MongoDBをローカルにインストールして立ち上げておいてください。
「MongoDBの薄い本」が参考になります。

あとpymongo入れといてください。pythonでMongoDB触るためのやつです。

かきこむ

"hogehoge"を準備でたてたMongoDBのなかにぶちこみます。

まずgetDBCollectionでローカルのMongoDBへのクライアントを用意して、コレクションを選択する。
あとはCollection.insert(formatToInsert("hogehoge"))で書き込むだけ。

Main.py
#-*- coding: utf-8 -*-

from pymongo import MongoClient

# DBの書き込み先を取得する
def getDBCollection():
    # LocalhostのMongoDBに書き込みます
    client = MongoClient()
    # LogsDBというDBを使います
    db = client.LogsDB
    # LogsCollectionというコレクションを使います
    Collection = db.LogsCollection
    return Collection

# データを書き込み用に変形する
def formatToInsert(Contents):
    # DBの  "キー名"     : "データ"   
    return {"Contents"  : Contents}

if __name__ == '__main__':
    Collection = getDBCollection()
    # コレクションにレコードを書き込みます
    while true:
        Collection.insert(formatToInsert("hogehoge"))
        time.sleep(10)
1
0
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
1
0