詳解Pymongo常用查詢方法總結

2022-09-26 11:45:21 字數 1262 閱讀 6018

1、安裝所需模組

使用到的是pymongo模組,安裝方法:pip install pymongo

2、環境驗證

3、連線資料庫

程式設計客棧

import pymongo

def operating_mongodb():

client = pymongo.mongoclient('ip_address', port)

db_auth = client.database

db_auth.authenticate("username", "password")

db =www.cppcns.com client.db_name

return db

4、連線到對應的資料庫表

mongodb = operating_

search_set = mongodb.table_name

5、按照所需欄位排序

search_set.find().sort("field_name ",pymongo.ascending) --公升序

search_set.find().sort("field_name ",pymongo.descending) --降序

6、查詢資料庫表的全部內容

第一種:search_set.find({})

第二種:search_set.find()

7、精確查詢

search_set.find()

search_set.find()

8、只返回所需要的字段資訊

find的第二引數可以幫助我們只把需要的鍵值資訊返回,需要將我們需要的鍵指定為1,

另外預設的」_id」預設是返回的,我們不需要它返回的話將它的值設為0

search_set.find({}, )

9、比較查詢

首先 $lt和

search_set.find(})

10、關聯查詢

如果只想查詢乙個鍵的多個值,或取除某個值之外所有的資料那麼就用到了

$in和$nin

比如我只想獲取field_name為1,5,8的資料:

search_set.find(})

如果想獲取field_njrbrlajrbrlme為5之外的所有資料:

search_set.find(})

11、多條件模糊查詢

$regex為模糊查詢的字串提供正規表示式功能

search_set.find(},}]})

通過這些常用的查詢方法,靈活組合,基本可以滿足常見的查詢需求

Pymongo常用查詢方法總結

python 直接連線mongodb資料庫進行查詢操作 1 安裝所需模組 使用到的是pymongo模組,安裝方法 pip install pymongo 2 環境驗證 3 連線資料庫 import pymongo def operating mongodb client pymongo.mongoc...

pymongo查詢列表元素 pymongo查詢技巧

from pymongo import mongoclient mdb mongoclient 120.20002 username password 資料240萬 no cursor timeout true代表連線不中斷,連續取 batch size 2000代表每批次取2000條 limit ...

pymongo模糊查詢

簡單來說就像下面這樣 1 import re 2 具體使用 正則進行匹配模型如下 from pymongo import mongoclient client mongoclient localhost 27017 預設配置 db client 資料庫名稱 c db 集合名稱 c.find 正則匹配...