国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Python > 正文

Pymongo庫簡單應用(Python的mongodb庫)

2024-07-21 02:52:08
字體:
來源:轉載
供稿:網友

Pymongo庫簡單應用

Pymongo庫是Python操作mongodb的庫。下面簡單介紹Pymongo的簡單使用。

創建mongo客戶端選擇數據庫和集合并插入數據

import pymongoclient = pymongo.MongoClient(host,port)#client = pymongo.MongoClient('mongodb://localhost:27017/')db = client.db #選擇名稱叫db的數據庫,沒有會創建#或者db = client['db']collection = db.test #選擇test名的collection,沒有會創建#或者collection = db['test']#collection 可以對集合進行操作collection.insert({'name':'aaa'}} #返回插入idcollection.insert([{'name':'aaa'},{'name':'bbb'}])#返回插入id的liste = collection.insert_one({'name':'ccc'})#返回結果通過e.inserted_id查看插入id

連接帶認證的mongo

上述連接可以連接不設置密碼的mongo,但是mongo帶密碼就需要其他的連接方式了。

#SCRAM-SHA-1方式uri = "mongodb://user:passWord@example.com/the_database?authMechanism=SCRAM-SHA-1"client = MongoClient(uri)#或者client = MongoClient('example.com')client.the_database.authenticate('user', 'password', mechanism='SCRAM-SHA-1')#MONGODB-CR 方式from pymongo import MongoClienturi = "mongodb://user:password@example.com/the_database?authMechanism=MONGODB-CR"client = MongoClient(uri)#或者client = MongoClient('example.com')client.the_database.authenticate('user', 'password', mechanism='MONGODB-CR')

查詢數據

a = collection.find({'name':'aaa'}) #返回游標,可以for迭代或者a.next()獲取a = collection.find_one({'name':'aaa'})#返回結果'''{'_id':ObjectId('58b92cdfc43b3735664597be'), 'name':'aaa'}'''#如果id是字符串類型的from bson.objectid import ObjectId #導入ObjectId把字符串id轉換成ObjectId才能查找collection.find_one({'_id':ObjectId('58b93904c43b3735664597c2')})#直接使用字符串id是無法查詢到內容的#查看數據條數collection.count()#或者 collection.find().count()collection.find({"name": "aaa"}).count()#條件查詢和排序d = datetime.datetime(2009, 11, 12, 12)posts.find({"date": {"$lt": d}}).sort("author")

創建索引

創建索引可以加快查詢

collection.create_index([('user_id',pymongo.ASCENDING),] ,unique=True)#創建一個唯一的不可重復的索引user_id,一次可以創建多個索引

參考官方文檔 http://api.mongodb.com/python/current/tutorial.html


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 丘北县| 定日县| 石棉县| 罗平县| 遵化市| 永胜县| 商丘市| 会宁县| 宿迁市| 宕昌县| 长丰县| 普宁市| 和静县| 昆明市| 抚顺市| 克山县| 阳泉市| 辽宁省| 香港| 安岳县| 邹城市| 昔阳县| 江门市| 遵化市| 信宜市| 南召县| 泰宁县| 姚安县| 盈江县| 大冶市| 尼勒克县| 荔波县| 富民县| 辉县市| 伊金霍洛旗| 黄石市| 抚宁县| 呼伦贝尔市| 方城县| 马山县| 永泰县|