pymongo基本用法

import pymongo

“”"------------------------------准备工作------------------------------------"""

连接数据库

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

选择数据库

db = client.mongo
db = client['mongo']

选择集合

collection = db.students
collections = db['students']

“”"------------------------------插入数据------------------------------------"""

#插入数据,推荐使用 insert_one 和 insert_many 两个函数分别用于插入一条数据和多条数据

student = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}
result = collection.insert_one(student)
print(result)

student1 = {
    'id': '20170102',
    'name': 'Bob',
    'age': 21,
    'gender': 'male'    
}

student2 = {
    'id': '20170103',
    'name': 'Mike',
    'age': 20,
    'gender': 'male'
}
result = collection.insert_many([student1, student2])
print(result)

“”"------------------------------查询数据------------------------------------"""

查询数据,推荐使用 find_one 和 find 函数两个函数分别用于查询一条数据和多条数据,find 返回生成器对象

result = collection.find_one({'name': 'Mike'})
print(type(result), result)

results = collection.find({'age': 20})
for r in results:
    print(r)

使用比较符号查询

"""
    $lt    小于             {'age': {'$lt': 20}}
    $gt    大于             {'age': {'$gt': 20}}
    $lte   小于等于         {'age': {'$lte': 20}}
    $gte   大于等于         {'age': {'$gte': 20}}
    $ne    不等于           {'age': {'$ne': 20}}
    $in    在范围内         {'age': {'$in': [20, 30]}}
    $nin   不在范围内       {'age': {'$nin': [20, 30]}}
"""
print(collection.find_one({'age': {'$gt': 20}}))

使用正则表达式查询

print(collection.find_one({'name': {'$regex': r'^M.*'}}))

“”"------------------------------更新数据------------------------------------"""

更新数据,推荐使用 update_one 和 update_many 更新一条或多条数据

condition = {'name': 'Mike'}
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition, {'$set': student})
print(result)
print(result.matched_count, result.modified_count)

使用 $inc 更新数据

result = collection.update_one(condition, {'$inc': {'age': 20}})
print(result)
print(result.matched_count, result.modified_count)

更新多条数据

result = collection.update_many(condition, {'$inc': {'age': 20}})
print(result)
print(result.matched_count, result.modified_count)

“”"------------------------------删除数据------------------------------------"""

推荐使用 delete_one 和 delete_many 分别用来删除一条和多条数据

result = collection.delete_one({'name': 'Mike'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'name': 'Bob'})
print(result)
print(result.deleted_count)
result = collection.delete_one({'age': {'$gt': 20}})
print(result)
print(result.deleted_count)

你可能感兴趣的:(工具)