天天看點

【MongoDB資料庫知識】MongoDB資料庫常見操作梳理MongoDB資料庫(端口:27017)

MongoDB資料庫(端口:27017)

1. MongoDB常用的操作

import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)

# 指定資料庫test
db = client.test

# 指定集合
collection = db.students

# 插入資料
student1 = {
    'id': '20180101',
    'name': 'zhangsan',
    'age': 20,
    'gender': 'male'
}
student2 = {
    'id': '20180102',
    'name': 'lisi',
    'age': 20,
    'gender': 'male'
}
result = collection.insert([student1, student2])
result = collection.insert_one(student1)
result = collection.insert_many([student1, student2])

# 查詢
result = collection.find_one({'name': 'zhangsan'})
results = collection.find({'age': 20})
for res in results:
    print(res)

# 年齡小于20的資料
results = collection.find({'age': {'$lt': 20}})
# 年齡小于等于20的資料
results = collection.find({'age': {'$lte': 20}})
# 年齡大于20的資料
results = collection.find({'age': {'$gt': 20}})
# 年齡大于等于20的資料
results = collection.find({'age': {'$gte': 20}})
# 年齡不等于20的資料
results = collection.find({'age': {'$ne': 20}})
# 年齡在[18, 25]範圍内的資料
results = collection.find({'age': {'$in': [18,23]}})
# 年齡不在[18, 25]範圍内的資料
results = collection.find({'age': {'$nin': [18,23]}})

# 正則查詢,比對以M開頭的資料
results = collection.find({'name': {'$regex': '^M.*'}})

# 計數
num = collection.find({'age': 20}).count()

# 根據字段,升序ASCENDING/降序DESCENDING
results = collection.find().sort('name', pymongo.ASCENDING)
print(result['name'] for result in results)

# 偏移位置,skip(n)忽略前n個元素
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print(result['name'] for result in results)

# 限制傳回結果個數limit(n),從左到右
results = collection.find().sort('name', pymongo.ASCENDING).limit(2)
print(result['name'] for result in results)

# 更新update()
condition = {'name': 'wangwu'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update(condition, student)

# $set操作符隻更新student字典記憶體在的字段,其他字段不更新也不删除
result = collection.update(condition, {'$set': student})

# update_one()
result = collection.update_one(condition, {'$set': student})
# 檢視獲得比對的資料條數和影響的資料條數
print(result.matched_count, result.modified_count)

# update_many()
condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 18})
# 檢視獲得比對的資料條數和影響的資料條數
print(result.matched_count, result.modified_count)

# 删除
result = collection.remove({'name': 'zhangsan'})
result = collection.delete_one({'name': 'zhangsan'})
result = collection.delete_many({'age': {'$lt': 20})
           

持續跟新,更多MongoDB資料庫知識,詳見個人部落格歸納。

歡迎留言補充,批評指正!