【MongoDB数据库知识】MongoDB数据库常见操作梳理

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数据库知识,详见个人博客归纳

欢迎留言补充,批评指正!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值