Google+ Followers

2014年1月22日 星期三

[Linux] MongoDB 與 PyMongo 初體驗 @ Ubuntu 12.04, Linode

架設:

http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
$ echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
$ sudo apt-get update

http://www.mongodb.org/downloads
$ sudo apt-get install mongodb-10gen=2.4.9
$ echo "mongodb-10gen hold" | sudo dpkg --set-selections

$ sudo service mongodb restart
mongodb stop/waiting
mongodb start/running, process ######

$ mongo
MongoDB shell version: 2.4.9
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        http://docs.mongodb.org/
Questions? Try the support group
        http://groups.google.com/group/mongodb-user


防火牆存取限制:

$ sudo iptables --list-rules
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT

$ sudo vim /etc/init.d/iptables-rule.sh
#!/bin/sh

# BIN
BIN_IPTABLES=`which iptables`

# reset rules
$BIN_IPTABLES -F
$BIN_IPTABLES -X
$BIN_IPTABLES -Z

# init policies
#$BIN_IPTABLES -P INPUT DROP
#$BIN_IPTABLES -P OUTPUT ACCEPT
#$BIN_IPTABLES -P FORWARD ACCEPT

# mongo db
$BIN_IPTABLES -A INPUT -j ACCEPT -p tcp --destination-port 27017 -s 127.0.0.1,IP1,IP2,IP3
# mongo db drop all
$BIN_IPTABLES -A INPUT -j REJECT -p tcp --destination-port 27017

$ sudo chmod 775 /etc/init.d/iptables-rule.sh
$ sudo update-rc.d -f iptables-rule.sh defaults


一些 mongo 常用指令:

顯示所有的 databases (SQL: show databases)
> show dbs

使用指定 collection (SQL: use dbname)
> use dbname

顯示目前 databases 中的所有 collections (SQL: show tables)
> show collections

更多對照指令:
SQL to MongoDB Mapping Chart
PHP: SQL to Mongo Mapping Chart


安裝 pymongo 套件:

$ git clone git://github.com/mongodb/mongo-python-driver.git pymongo
$ cd pymongo
$ sudo python setup.py install


使用 pymongo 新增範例:

from pymongo import MongoClient

client = MongoClient()
database = client[‘dbname’] # SQL: Database Name
collection = database[‘table’]   # SQL: Table Name

item = {"author":"changyy"}
collection.insert(item)


沒有留言:

張貼留言