Python 操作mongodb 简单实例

  1、建立数据库用户

    要读写 mongo数据库,默认没有用户名和密码也可以对数据库进行读写操作,但是从安全的角度,最好给要操作的数据库建立用户名和密码。

    打开mongo数据库服务,打开mongo.exe,建立用户

    具体的用户权限参照:http://www.cnblogs.com/shaosks/p/6589867.html

    注意:下面的创建用户的角色是:dbOwner,按说读写数据库用户权限用readWrite就可以了,但是好像用readWrite,在用程序验证的报错,没有办法就用了dbOwner角色

 use admin
switched to db admin
> db.auth("myUserAdmin","mypass123")
1
> use OTT_DB
switched to db OTT_DB
> db.createUser(
... ... ... ...  {
... ... ... ...     user: "ott_test",
... ... ... ...    pwd: "ott_test",
... ... ... ...     roles: [
... ... ... ...       { role: "dbOwner", db: "OTT_DB" },
... ... ... ...    ]
... ... ... ...  }
... ... ... ...  )
Successfully added user: {
        "user" : "ott_test",
        "roles" : [
                {
                        "role" : "dbOwner",
                        "db" : "OTT_DB"
                }
        ]
}
> db.auth("ott_test","ott_test")
1
> db.test.insert({name:"mike"})
WriteResult({ "nInserted" : 1 })
>

 

  2、访问代码

# coding=utf-8
from pymongo import ASCENDING, DESCENDING
from pymongo import MongoClient
import codecs
import time
import os
import datetime
from pyExcelerator import *
import csv
class mongoDbBase:

    def __init__(self, databaseIp = '127.0.0.1',databasePort = 27017,user = "ott",password= "ott", mongodbName='OTT_DB'):

        client = MongoClient(databaseIp,databasePort)
        self.db = client[mongodbName]
        self.db.authenticate(user,password)

    def saveTestInfo(self):
        dict = {"name":"大山"}
        self.db.test.insert(dict)



obj = mongoDbBase()
obj.saveTestInfo()

 

posted on 2017-11-01 15:06  shaomine  阅读(2471)  评论(0编辑  收藏  举报