1. 程式人生 > >java程式設計師的python之路(mongodb)

java程式設計師的python之路(mongodb)

建立mongodb使用者

mongo的安裝我們就不提了,這裡使用的mongo版本是3.4。首先我們啟動mongo,啟動命令如下:

./bin/mongod -f bin/mongodb.conf

mongodb.conf的檔案內容如下:

dbpath=/data/lehoo/software/mongodb/data/db
logpath=/data/lehoo/software/mongodb/data/log/mongo.log
pidfilepath=/data/lehoo/software/mongodb/mongo.pid
port=27017
fork=true
auth=false

dbpath和logpath可以自行指定,需要注意的是設定auth=false,我們需要使用非驗證模式登入,建立一個超級使用者,命令如下:

[root@Master mongodb]# ./bin/mongo
MongoDB shell version v3.4.4
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.4
> show dbs
admin  0.000GB
local  0.000GB
> use admin
switched to db admin
> show collections
system.version
> db.createUser({user:"root", pwd:"root",roles: [{role:"root"
,db:"admin"}]}) Successfully added user: { "user" : "root", "roles" : [ { "role" : "root", "db" : "admin" } ] } > show collections system.users system.version > db.system.users.find() { "_id" : "admin.root", "user" : "root", "db" : "admin", "credentials"
: { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "h85b/3AU27wIiqDkNc++TQ==", "storedKey" : "lLvHeEialDyfLN4C1AVc81QUQGA=", "serverKey" : "zgfZzcI0CxVueijCc4Egz035jJo=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] } >

到這裡我們就建立了一個超級使用者,root。退出mongo,修改auth=true,命令如下:

> exit
bye
[root@Master mongodb]# ./bin/mongod -f bin/mongodb.conf -shutdown
killing process with pid: 2625
[root@Master mongodb]# 

修改mongodb.conf檔案內容如下:

dbpath=/data/lehoo/software/mongodb/data/db
logpath=/data/lehoo/software/mongodb/data/log/mongo.log
pidfilepath=/data/lehoo/software/mongodb/mongo.pid
port=27017
fork=true
auth=true

再次啟動mongo,並使用root使用者驗證,命令如下:

[[email protected] bin]# ./mongod -f mongodb.conf 
about to fork child process, waiting until server is ready for connections.
forked process: 4967
child process started successfully, parent exiting

[[email protected] bin]# ./mongo
MongoDB shell version v3.4.4
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.4

> use admin
switched to db admin
> db.auth("root","root")
1
> 

使用db.auth來驗證,輸出結果是1,說明驗證通過,下一步我們就使用root使用者來建立我們自己的資料庫和使用者,資料庫名為test,使用者名稱為test。命令如下:

> use test
switched to db test
> db.createUser({user:"test",pwd: "test",roles:[{role:"dbOwner",db:"test"}]})
Successfully added user: {
    "user" : "test",
    "roles" : [
        {
            "role" : "dbOwner",
            "db" : "test"
        }
    ]
}
> use admin
switched to db admin
> db.system.users.find()
{ "_id" : "admin.root", "user" : "root", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "h85b/3AU27wIiqDkNc++TQ==", "storedKey" : "lLvHeEialDyfLN4C1AVc81QUQGA=", "serverKey" : "zgfZzcI0CxVueijCc4Egz035jJo=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "test.test", "user" : "test", "db" : "test", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "XyUa5iXZd4DNram39wDWvA==", "storedKey" : "T/nxudYpTRtNkE9DmUtBLfKSHp4=", "serverKey" : "lbqv8A2DDjaC5peHpGWPqr6jDWk=" } }, "roles" : [ { "role" : "dbOwner", "db" : "test" } ] }
> use test
switched to db test
> db.auth("test","test")
1
> 

建立成功,返回admin資料庫檢視users表中,多出了一個使用者,然後再返回test資料庫,使用db.auth驗證test使用者通過。那麼我們現在就可以使用test使用者來操作test資料庫了。下面我們介紹python操作mongodb。

安裝pymongo

python的安裝這裡也不再介紹,這裡使用的python版本是3.6.0。我們使用pip的方式安裝pymongo,命令如下所示:

[[email protected] software]# python -V
Python 3.6.0
[[email protected] software]# python -m pip install pymongo
Collecting pymongo
  Downloading pymongo-3.4.0.tar.gz (583kB)
    100% |████████████████████████████████| 583kB 23kB/s 
Installing collected packages: pymongo
  Running setup.py install for pymongo ... done
Successfully installed pymongo-3.4.0
[[email protected] software]# 

CRUD

上面我們已經準備好了資料庫,也安裝上了pymongo,這裡使用pymongo來做簡單的增刪改查操作,操作比較簡單直接看程式碼:

from pymongo import MongoClient

#連線字串   mongodb://[username:[email protected]]host1[:port1]]][/[database][?options]]
client = MongoClient("mongodb://test:[email protected]:27017/test?authMechanism=SCRAM-SHA-1") #MONGODB-CR
db = client["test"]

#插入
db.users.insert({"name":"aaa","age":20})#單條插入
db.users.save({"name":"aaa","age":20})#單條插入
db.users.insert([{"name":"bbb","age":21},{"name":"ccc","age":22}])#多條插入

#修改
db.users.update({"name":"aaa"},{"$set":{"age":2}})#單條修改
db.users.update_many({"name":"aaa"},{"$set":{"age":2}})#多條修改

#查詢
user = db.users.find_one({"name":"aaa"})#單條查詢
print(user["name"],user["age"])


data = db.users.find({"name":"aaa"})#多條查詢
for user in data:
    print(user["name"],user["age"])


#刪除
db.users.remove({"name":"aaa"})
db.users.remove()#刪除全部資料    


client.close()    

輸出結果如下:

aaa 2
aaa 2
aaa 2

我們看到使用pymongo來操作mongo的語句和使用mongo命令基本相同。還是很親切的。

自定義物件

怎麼把python的物件,儲存到mongodb中呢?基本思路就是把物件轉化成字典結構,然後再儲存。反之就是把字典結構轉化為物件。直接看程式碼:

from pymongo import MongoClient

class User():
    def __init__(self,name="",age=0,address=None):
        self.name = name
        self.age = age
        self.address = address

    #轉化為字典結構
    def toMap(self):
        return {"name":self.name,"age":self.age,"address":self.address.toMap()}

    #轉化為物件
    def fromDb(self,data):
        self.name = data["name"]
        self.age = data["age"]
        self.address = Address()
        self.address.fromDb(data["address"])

class Address():
    def __init__(self,country="",city=""):
        self.country = country
        self.city = city

    #轉化為字典結構
    def toMap(self):
        return {"country":self.country,"city":self.city}

    #轉化為物件
    def fromDb(self,data):
        self.country = data["country"]
        self.city = data["city"]



#建立連線
client = MongoClient("mongodb://test:[email protected]:27017/test?authMechanism=SCRAM-SHA-1") #MONGODB-CR
db = client["test"]

#建立物件
address = Address("CN","BeiJing")
user = User("aaa",20,address)

#把物件轉化為字典
data = user.toMap()
print(data)

#插入資料庫
db.users.insert(data)

#查詢資料庫
result = db.users.find_one({"name":"aaa"})

#把結構轉化為物件
user1 = User()
user1.fromDb(result)
print(user1.toMap())

#刪除資料
db.users.remove()

client.close()

輸出結果如下:

{'age': 20, 'address': {'country': 'CN', 'city': 'BeiJing'}, 'name': 'aaa'}
{'age': 20, 'address': {'country': 'CN', 'city': 'BeiJing'}, 'name': 'aaa'}

前後物件的資料完全一致,說明操作成功。
pymongo操作mongo資料庫還有很多複雜高階的操作,比如高階查詢,排序,分組,Map,Reduce等。這裡就介紹簡單的入門操作,需要自行發掘。