⑴ 如何提升python操作mongodb的效率
對於大規模的遍歷,我覺得可以考慮:
使用EXHAUST類型的cursor,這樣可以讓mongo一批一批的返回查詢結果,並且在client請求之前把數據stream過來。
在find指定batch_size,默認值貌似是101個document或者size超過1M,可以設定更大的batch_size來指定route trip的數量,詳
⑵ python 怎樣通過遍歷以下文件後全部讀到mongodb資料庫中
python 訪問 mongodb 需要先安裝 pymongo,如下:
1pipinstallpymongotxt 文件格式:
代碼如下:
⑶ 怎麼使用python編寫根據輸入查詢條件查詢mongoDB資料庫
hid=239526
cur = my_set.find({"sourceID":1,"downloadDate":"2018-05-08","bwHotelID":hid},{"checkIn":1,"_id":0}).sort([("checkIn",1)])
查詢條件參數化, 這里是josn格式,不是這字元串,不用佔位符之類的東西
你要知道json對象就等同於你的python代碼
你在它那直接用變數代替就行
⑷ python中mongodb怎麼連接其他伺服器的資料庫
1、基於mongo實現遠程連接
[plain] view plain
mongo -u admin -p admin 192.168.0.197:27017/pagedb
通過mongo實現連接,可以非常靈活的選擇參數選項,參看命令幫助,如下所示:
[plain] view plain
mongo --help
MongoDB shell version: 1.8.3
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
foo foo database on local machine
192.169.0.5/foo foo database on 192.168.0.5 machine
192.169.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999
options:
--shell run the shell after executing files
--nodb don't connect to mongod on startup - no 'db address'
arg expected
--quiet be less chatty
--port arg port to connect to
--host arg server to connect to
--eval arg evaluate javascript
-u [ --username ] arg username for authentication
-p [ --password ] arg password for authentication
-h [ --help ] show this usage information
--version show version information
--verbose increase verbosity
--ipv6 enable IPv6 support (disabled by default)
2、基於MongoDB支持的javascript實現遠程連接
當你已經連接到一個遠程的MongoDB資料庫伺服器(例如,通過mongo連接到192.168.0.184),現在想要在這個會話中連接另一個遠程的資料庫伺服器(192.168.0.197),可以執行如下命令:
[plain] view plain
> var x = new Mongo('192.168.0.197:27017')
> var ydb = x.getDB('pagedb');
> use ydb
switched to db ydb
> db
ydb
> ydb.page.findOne()
{
"_id" : ObjectId("4eded6a5bf3bfa0014000003"),
"content" : "巴黎是浪漫的城市,可是...",
"pubdate" : "2006-03-19",
"title" : "巴黎:從布魯塞爾趕到巴黎",
"url" : "http://france.bytravel.cn/Scenery/528/cblsegdbl.html"
}
上述通過MongoDB提供的JavaScript腳本,實現對另一個遠程資料庫伺服器進行連接,操作指定資料庫pagedb的page集合。
如果啟用了安全認證模式,可以在獲取資料庫連接實例時,指定認證賬號,例如:
[plain] view plain
> var x = new Mongo('192.168.0.197:27017')
> var ydb = x.getDB('pagedb', 'shirdrn', '(jkfFS$343$_\=\,.F@3');
> use ydb
switched to db ydb
⑸ 各位大腦,如何把txt文件用python導入到mongoDB資料庫里txt裡面欄位是姓名學號成績
python 訪問 mongodb 需要先安裝 pymongo,如下:
pipinstallpymongo
txt 文件格式:
#coding=utf-8
frompymongoimportMongoClient
conn=MongoClient('127.0.0.1',27017)
#連接test資料庫,沒有則自動創建
db=conn.test
#使用students集合,沒有則自動創建
students=db.students
#打開學生信息文件,並將數據存入到資料庫
withopen('students.txt','r')asf:
forlineinf.readlines():
#分割學生信息
items=line.strip('
').strip('
').split(',')
#添加到資料庫
students.insert({'stu_id':items[0],'name':items[1],'grade':int(items[2])})
#資料庫查詢學生信息並列印出來
forsinstudents.find():
print(s)
⑹ Python語言怎麼實現mongodb的查詢操作
對於mongo的操作,先安裝mongodb的python擴展,在你的命令行窗口上輸入:pip install pymongo,下面是例子,按需要修改
frompymongoimportMongoClient
importtime
mongo_uri_auth='mongodb://user:password@localhost:27017/'#mongo有要驗證的話請自行替換user和password
mongo_uri_no_auth='mongodb://localhost:27017/'#mongo沒有賬號密碼驗證的時候用這個
database_name='request_db'#你要連接的資料庫名,自行替換你需要的庫名
table_name='request_tb'#你要查詢的表名,請自行替換你需要的表名
client=MongoClient(mongo_uri_no_auth)#創建了與mongodb的連接
db=client[database_name]
table=db[table_name]#獲取資料庫中表的游標
#你要插入的數據
insert_data={"name":"Mike","grade":"two","age":12,"sex":"man"}
table..insert_one(insert_data)#插入一條數據
#查詢數據name為Mike的記錄
record=table.find_one({"name":"Mike"})
printrecord
⑺ python怎麼操作mongodb
#coding:utf-8__author__ = 'hdfs'import pymongofrom pymongo import MongoClientclient = MongoClient() client=MongoClient('10.0.0.9',27017)#連接mongodb資料庫client = MongoClient('mongodb://10.0.0.9:27017/')#指定資料庫名稱db = client.test_database#獲取非系統的集合db.collection_names(include_system_collections=False)#獲取集合名posts = db.posts#查找單個文檔posts.find_one()#給定條件的一個文檔posts.find_one({"author": "Mike"})#使用ID查找需要ObjectIDfrom bson.objectid import ObjectIdpost_id='5728aaa96795e21b91c1aaf0'document = client.db.collection.find_one({'_id': ObjectId(post_id)})import datetimenew_posts = [{"author": "Mike", "text": "Another post!", "tags": ["bulk", "insert"], "date": datetime.datetime(2009, 11, 12, 11, 14)}, {"author": "Eliot", "title": "MongoDB is fun", "text": "and pretty easy too!", "date": datetime.datetime(2009, 11, 10, 10, 45)}]#插入多條記錄result = posts.insert_many(new_posts)#返回插入的IDresult.inserted_ids#遞歸集合for post in posts.find(): post #遞歸條件集合for post in posts.find({"author": "Mike"}): post #文檔的記錄數posts.count() #區間查詢d = datetime.datetime(2009, 11, 12, 12)for post in posts.find({"date": {"$lt": d}}).sort("author"): print post#給集合profiles建立索引 唯一索引result = db.profiles.create_index([('user_id', pymongo.ASCENDING)],unique=True)#查看索引信息list(db.profiles.index_information())#user_profiles = [{'user_id': 211, 'name': 'Luke'},{'user_id': 212, 'name': 'Ziltoid'}]result = db.profiles.insert_many(user_profiles) #聚合查詢from pymongo import MongoClientdb = MongoClient('mongodb://10.0.0.9:27017/').aggregation_example#准備數據result = db.things.insert_many([{"x": 1, "tags": ["dog", "cat"]}, {"x": 2, "tags": ["cat"]}, {"x": 2, "tags": ["mouse", "cat", "dog"]}, {"x": 3, "tags": []}])result.inserted_ids'''{ "_id" : ObjectId("576aaa973e5269020848cc7c"), "x" : 1, "tags" : [ "dog", "cat" ] }{ "_id" : ObjectId("576aaa973e5269020848cc7d"), "x" : 2, "tags" : [ "cat" ] }{ "_id" : ObjectId("576aaa973e5269020848cc7e"), "x" : 2, "tags" : [ "mouse", "cat", "dog" ] }{ "_id" : ObjectId("576aaa973e5269020848cc7f"), "x" : 3, "tags" : [ ] }'''from bson.son import SON#$unwind 解開-後面的變數pipeline = [ {"$unwind": "$tags"}, {"$group": {"_id": "$tags", "count": {"$sum": 1}}}, {"$sort": SON([("count", -1), ("_id", -1)])} ]list(db.things.aggregate(pipeline))#使用聚合函數with commanddb.command('aggregate', 'things', pipeline=pipeline, explain=True)
⑻ 怎樣使用python訪問mongodb
安裝驅動pymongo!
輸入命令:pip installpymongo
直接使用驅動
缺點:
不是全盤取代傳統資料庫(NoSQLFan:是否能取代需要看應用場景)
不支持復雜事務(NoSQLFan:MongoDB只支持對單個文檔的原子操作)
文檔中的整個樹,不易搜索,4MB限制?(NoSQLFan:1.8版本已經修改為16M)
特點(NoSQLFan:作者在這里列舉的很多隻是一些表層的特點):
文檔型資料庫,表結構可以內嵌
沒有模式,避免空欄位開銷(Schema Free)
分布式支持
查詢支持正則
動態擴展架構
32位的版本最多隻能存儲2.5GB的數據(NoSQLFan:最大文件尺寸為2G,生產環境推薦64位)
⑼ python 連mongodb時怎麼設定mongod服務端路徑
python連接mongodb操作數據示例,主要包括插入數據、更新數據、查詢數據、刪除數據等
一、相關代碼
資料庫配置類 MongoDBConn.py
復制代碼 代碼如下:
#encoding=utf-8
'''
Mongo Conn連接類
'''
import pymongo
class DBConn:
conn = None
servers = "mongodb://localhost:27017"
def connect(self):
self.conn = pymongo.Connection(self.servers)
def close(self):
return self.conn.disconnect()
def getConn(self):
return self.conn
MongoDemo.py 類
復制代碼 代碼如下:
#encoding=utf-8
'''
Mongo操作Demo
Done:
'''
import MongoDBConn
dbconn = MongoDBConn.DBConn()
conn = None
lifeba_users = None
def process():
#建立連接
dbconn.connect()
global conn
conn = dbconn.getConn()
#列出server_info信息
print conn.server_info()
#列出全部資料庫
databases = conn.database_names()
print databases
#刪除庫和表
dropTable()
#添加資料庫lifeba及表(collections)users
createTable()
#插入數據
insertDatas()
#更新數據
updateData()
#查詢數據
queryData()
#刪除數據
deleteData()
#釋放連接
dbconn.close()
def insertDatas():
datas=[{"name":"steven1","realname":"測試1","age":25},
{"name":"steven2","realname":"測試2","age":26},
{"name":"steven1","realname":"測試3","age":23}]
lifeba_users.insert(datas)
def updateData():
'''只修改最後一條匹配到的數據
第3個參數設置為True,沒找到該數據就添加一條
第4個參數設置為True,有多條記錄就不更新
'''
lifeba_users.update({'name':'steven1'},{'$set':{'realname':'測試1修改'}}, False,False)
def deleteData():
lifeba_users.remove({'name':'steven1'})
def queryData():
#查詢全部數據
rows = lifeba_users.find()
printResult(rows)
#查詢一個數據
print lifeba_users.find_one()
#帶條件查詢
printResult(lifeba_users.find({'name':'steven2'}))
printResult(lifeba_users.find({'name':{'$gt':25}}))
def createTable():
'''創建庫和表'''
global lifeba_users
lifeba_users = conn.lifeba.users
def dropTable():
'''刪除表'''
global conn
conn.drop_database("lifeba")
def printResult(rows):
for row in rows:
for key in row.keys():#遍歷字典
print row[key], #加, 不換行列印
print ''
if __name__ == '__main__':
process()