MongoDB基本操作

连接数据库

import pymongo

client = pymongo.MongoClient(host='localhost', port=2701

指定数据库

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
# or
db = client['test']

插入数据

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
# or
db = client['test']

# 指定集合
collection = db.student
# or
collection = db['student']

student = {
    'id' : '2019210050',
    'user' : 'wiselisx',
    'age' : 22,
    'gender' : 'male'
}

student1 = {
    'id' : '2019210050',
    'user' : 'wiselisx',
    'age' : 23,
    'gender' : 'male'
}

# 插入单条数据
result = collection.insert_one(student)

# 插入多条数据
result = collection.insert_many([student, student1])

查询数据

# 查询名字为Mikes的数据
result = collection.find_one({'name': 'Mike'})
# 查询所有名字为Mikes的数据
result = collection.find({'name': 'Mike'})
# 查询年龄大于20的数据
result = collection.find({'age': {'$gt': 20}})
# 正则表达式查询
result = collection.find({'name': {'$regex': '^M.*'}})

计数

# 计数
count = collection.find().count()
# 符合某个条件的计数
count = collection.find({'age': {'$gt': 20}}).count()

排序

# 排序
results = collection.fin().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])

偏移

# 排序之后只取几个结果数
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
# 限制取几个数
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)

更新数据

# 更新单条数据
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update_one(condition, {'$set': student})

# 更新多条数据
condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})

删除

# 删除单条数据
condition = {'name': 'Kevin'}
result = collection.delete_one(condition)

# 删除多条数据
condition = {'age': {'$gt': 20}}
result = collection.delete_many(condition)

其它

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值