MongoDB を試してみる
2020-10-24-1
[Programming][Python]
今更ながら、MongoDB を macOS と CentOS7 で試してみた。ざっくりとだけど一通り流れは理解できた。
目的の一つは、ある商品群の価格変化を記録していくこと。Keepa みたいなイメージ。私がよくやっている「TSVファイルに追加していく単純な方式」と比べ、速度や使い勝手がどうなのかは、サーバで運用しながら調べていく予定。
これらを参考に。
起動:
MongoDB の current version は 4.4。
ここの手順に従う。
まず、"/etc/yum.repos.d/mongodb-org-4.4.repo" を作り、それから yum を実行。
起動:
目的の一つは、ある商品群の価格変化を記録していくこと。Keepa みたいなイメージ。私がよくやっている「TSVファイルに追加していく単純な方式」と比べ、速度や使い勝手がどうなのかは、サーバで運用しながら調べていく予定。
macOS へのインストール
環境: MacBook Pro (13-inch, 2017), macOS 10.15.7。これらを参考に。
今はできない。代わりの方法。brew install mongodb
brew tap mongodb/brew brew install mongodb-community cat /usr/local/etc/mongod.conf systemLog: destination: file path: /usr/local/var/log/mongodb/mongo.log logAppend: true storage: dbPath: /usr/local/var/mongodb net: bindIp: 127.0.0.1
起動:
brew services start mongodb-community
CentOS7 へのインストール
環境: さくらVPS, CentOS 7。MongoDB の current version は 4.4。
ここの手順に従う。
まず、"/etc/yum.repos.d/mongodb-org-4.4.repo" を作り、それから yum を実行。
sudo yum install -y mongodb-org
起動:
sudo systemctl start mongod
動作の確認
mongo
use test
show dbs
db.stats()
# db.createCollection('hello')
show collections
db.hello.stats()
db.hello.insert({'uid':123, 'test':'World'})
db.hello.insert({'uid':"oreore", 'text':'This is a pen.'})
db.hello.insert({'uid':"you", 'text':'Today is ...'})
db.hello.find()
db.hello.findOne()
db.hello.findOne()["uid"]
var r = db.hello.find()
while (r.hasNext()) printjson(r.next())
quit()
バックアップ&リストア
mongodump -d test mongo use test db.hello.drop() db.dropDatabase() show dbs quit() mongorestore ./dump
監視
mongotop mongostat
取り出し
db.hello.find({}, {uid: 1, text: 1, _id: 0})
db.hello.find({$or: [{'uid':123}, {'uid':"you"}]}, {uid: 1, text: 1, _id: 0})
db.hello.find({$or: [{'uid':123}, {'uid':"you"}, {'uid':"oreore"}]}, {ud: 1, text: 1, _id: 0})
db.hello.find({$or: [{'uid':123}, {'uid':"you"}, {'uid':"NO"}]}, {uid: 1, text: 1, _id: 0})
更新
db.hello.update({"uid" : "you"}, {$set : {"text":"こんにちは"}})
db.hello.insert({'uid':"me", 'hist':[{'ymd':20201020,'val':12}]})
db.hello.update({'uid':"me"}, {$push:{'hist':{'ymd':20201024,'val':38}}})
db.hello.update({'uid':"me"}, {$set:{'last-update':ISODate("2020-10-24T12:55:15")}})
Python
インストール:テストスクリプト:pip install pymongo
from pymongo import MongoClient
import datetime
dt_now = datetime.datetime.now()
client = MongoClient('localhost',27017)
db = client.test
col = db.hello
for i in col.find():
print(i)
col.update_one({'uid':"me"}, {
'$push':{'hist':{'ymd':dt_now,'val':189}},
'$set':{'last-update':dt_now}
})
print(col.find_one({'uid':"me"}))
