出處: Youtube 彭彭的課程 Python Flask 網站後端開發 – MongoDB 篩選、排序資料
實作筆記
篩選集合中的文件資料
想搜尋”number”:”1″的資料


#篩選集合中的文件資料
doc = collection.find_one({
"number":"1"
})
print("取得的資料",doc)


如果想搜尋特定欄位也可以用
print(“取得的資料”,doc[“name”])去過濾。。。
如果”number”:”1″ 這一筆資料不只一筆的話也只會印出一筆,只會列出id較舊的資料,先被創先贏的概念
同時成立的條件$and
接下來想篩選number”:”3″,並且”password”是6789

#複合篩選條件
doc = collection.find_one({
"$and":[
{"number":"3"},
{"password":6789}
]
})
print("取得的資料",doc)

滿足其中一條件$or
接下來想篩選number”:”1″,或是”password”是6789


#複合篩選條件
doc = collection.find({
"$or":[
{"number":"1"},
{"password":6789}
]
})
for n in doc:
print("取得的資料",n)
#篩選結果排序
- 由於篩選的結果會有復數筆資料, 若用一筆條件去抓的話collection.find_one,那就只能抓到一筆資料,所以用collection.find 復數的條件去抓
- 這邊的 變數doc是一個物件,若沒有用for迴圈的話,會印出類似這樣的結果<pymongo.cursor.Cursor object at 0x000001BFEDD408B0>,所以必須用for迴圈把每筆資料在印出來
結果

排序方式 sort
排序分別可以由小至大(ascending; 預設),或由大至小(descending)。
以下想要“number”由大至小進行排列
#篩選結果排序
doc = collection.find({
"$or":[
{"number":"3"},
{"password":123}
]
}, sort=[
("number",pymongo.DESCENDING)
]
)
for n in doc:
print("取得的資料",n)


“number”由大至小進行排列(ascending; 預設)
sort=[
("number",pymongo.ASCENDING)
