連接數據庫
import pymongo
# 連接到數據庫,以下兩種方式均可
client = pymongo.MongoClient(host='localhost', port=27017)
client = pymongo.MongoClient('mongodb://localhost:27017')
# 指定連接的數據庫,以下兩種方式均可
db = client.demo
db = client['demo']
# 指定數據庫的某個集合,以下兩種方式均可
collection = db.demo_1
collection = db['demo_1']
插入數據
- insert_one(), 一次插入一條記錄
- insert_many(), 一次插入多條記錄
mongo默認會給每一條記錄添加一個_id字段,用來唯一標識每一條記錄。
# 一次插入一條記錄
book = {
'name': '五年高考三年模擬',
'price': 50,
}
result = collection.insert_one(book)
print(result.inserted_id)
# 一次插入多條數據
book = [
{
'name': '五年高考',
'price': 50,
},
{
'name': '三年模擬',
'price': 30,
},
]
resutl = collection.insert_many(book)
可以使用result.inserted_id
和result.inserted_ids
來查看插入記錄的_id編號。
查詢數據
- find_one(), 查詢一條記錄, 以字典的形式直接返回數據結果。
- find(), 查詢多條記錄, 返回的是Cursor對象,需要遍歷才能獲取數據
# 查詢單條記錄
results = collection.find_one({'name': '五年高考'})
print(result)
# 查詢多條記錄
results = collection.find({'price': 50})
for result in results:
print(result)
mongo提供了一些高級的查詢參數來實現更加靈活的數據查詢。
比較運算符
符號 | 含義 | 例子 |
---|---|---|
$lt | 小於 | {'price': {'$lt':50}} |
$gt | 大於 | {'price': {'$gt':30}} |
$lte | 小於等於 | {'price': {'$lte':40}} |
$gte | 大於等於 | {'price': {'$lte':30}} |
$ne | 不等於 | {'price': {'$ne':30}} |
$in | 在范圍內 | {'price': {'$in':[30,50]}} |
$nin | 不在范圍內 | {'price': {'$nin':[30,40]}} |
正則表達式
符號 | 含義 | 例子 |
---|---|---|
$regex | 匹配正則 | {'name': {'$regex': '^M.*'}} |
$exists | 屬性是否存在 | {'name': {'$exists': True}} |
$type | 類型判斷 | {'age': {'$type': 'int'}} |
$mod | 數字模操作 | {'age': {'$mod': [5, 0]}} |
$text | 文本查詢 | {'$text': {'$search': 'Mike'}} |
$where | 高級條件查詢 | {'$where': 'obj.fans_count == obj.follows_count'} |
更新數據
- update_one(), 只更新匹配到的第一條記錄
- update_many(), 更新匹配到的全部記錄
condition = {'name':'五年高考'}
price_change = {'price': 100}
# 方式1
result = collection.update_one(condition,price_change)
print(result)
# 方式2
result = collection.update_one(condition, {'$set': price_change})
print(result)
以上兩種方式都是更新name為五年高考的字段,但是其結果卻是不同的
方式一:
相當於查詢到name為五年高考的字段,將其刪除,再將待更新的數據添加上去。結果就是只剩下一個price為100的數據。
方式二:
查詢到name為五年高考的字段,僅僅是將price更新為了100,其余不動。
另外可以調用result.matched_count, result.modified_count
來查看匹配的條數和影響的條數。
刪除數據
- delete_one(), 刪除符合條件的第一條數據
- delete_many(), 刪除符合條件的全部數據
# 刪除一條
result = collection.delete_one({'name': '五年高考'})
print(result)
# 刪除多條
result = collection.delete_many({'price':50}) # 刪除價格為50的全部記錄
result = collection.delete_many({'price':{'$gt':30}}) # 刪除價格大於30的全部記錄
另外可以調用result.deleted_count
查看刪除的條數。
其他常用方法
- count()
count = collection.find().count() # 查詢表中全部記錄的條數
count = collection.find({'price': {'$gt':30}}).count() # 價格大於30的條數
- sort()
results = collection.find().sort('name', pymongo.ASCENDING) # 按照name升序返回結果
results = collection.find().sort('price', pymongo.DECENDING) # 按照price降序返回結果
- limit()
results = collection.find().sort('name', pymongo.ASCENDING).limit(2) # 限制返回兩條結果