Python操作MongoDB

MongoDB是专为可扩展性,高性能和高可用性而设计的Nosql数据库。

安装配置

MongoDB下载地址
$ pip install pymongo

连接MongoDB

连接方式有如下两种
传入MongoDB的IP及端口即可,其中第一个参数为地址host,第二个参数为端口port

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

MongoClient的第一个参数host还可以直接传入MongoDB的连接字符串
client = MongoClient('mongodb://localhost:27017/')

指定数据库

db = client.test
OR
db = client['test']
两种方式等价

指定集合

MongoDB的每个数据库又包含许多集合(collection),它们类似于关系型数据库中的表。

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

插入数据

  • insert_one
student = {
    '_id':1,
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}

result = collection.insert_one(student)
print(result)
print(result.inserted_id)
  • insert_many
student1 = {
    '_id':1,
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}
student2 = {
    '_id':2,
    'id': '20170101',
    'name': 'JoJo',
    'age': 20,
    'gender': 'male'
}

result = collection.insert_many([student1,student2])
print(result)
print(result.inserted_ids)

查询数据

插入数据后,我们可以利用find_one()或find()方法进行查询,其中find_one()查询得到的是单个结果,find()则返回一个生成器对象

  • find_one
result = collection.find_one({'name':'JoJo'})
print(result)
  • find
result = collection.find({'gender':'male'})
print(list(result))

比较符号

results = collection.find({'age': {'$gt': 20}})

符号含义示例
$lt小于{'age': {'$lt': 20}}
$gt大于{'age': {'$gt': 20}}
$lte小于等于{'age': {'$lte': 20}}
$gte大于等于{'age': {'$gte': 20}}
$ne不等于{'age': {'$ne': 20}}
$in在范围内{'age': {'$in': [20, 23]}}
$nin不在范围内{'age': {'$nin': [20, 23]}}

功能符号

results = collection.find({'name': {'$regex': '^M.*'}})

符号含义示例示例含义
$regex匹配正则表达式{'name': {'$regex': '^M.*'}}name以M开头
$exists属性是否存在{'name': {'$exists': True}}筛选出name属性存在的数据
$type类型判断{'age': {'$type': 'int'}}age的类型为int
$mod数字模操作{'age': {'$mod': [5, 0]}}年龄模5余0
$text文本查询{'$text': {'$search': 'Mike'}}text类型的属性中包含Mike字符串
$where高级条件查询{'$where': 'obj.fans_count == obj.follows_count'}自身粉丝数等于关注数

计数

count = collection.find().count()
print(count)

排序

排序时,直接调用sort()方法,并在其中传入排序的字段及升降序标志即可。
pymongo.ASCENDING指定升序,pymongo.DESCENDING指定降序。

results = collection.find().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])

偏移和限制

在某些情况下,我们可能想只取某几个元素,这时可以利用skip()方法偏移几个位置,比如偏移2,就忽略前两个元素,得到第三个及以后的元素:

  • skip
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])
  • limit
result = collection.find().limit(2)
print([r['name'] for r in result])

更新

对于数据更新,我们可以使用update()方法,指定更新的条件和更新后的数据即可。例如:

condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update(condition, student)
print(result)

删除

删除操作比较简单,直接调用remove()方法指定删除的条件即可,此时符合条件的所有数据均会被删除。

result = collection.remove({'name': 'Kevin'})
print(result)

另外,这里依然存在两个新的推荐方法——delete_one()和delete_many()

result = collection.delete_one({'name': 'Kevin'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)

导入数据

mongoimport支持json,csv两种数据格式
$ mongoimport -d database -c collection --type csv --headerline --file /root/demo.csv
--type:指明要导入的文件格式
--headerline:指明第一行是列名,不需要导入
--file:指明要导入的文件

基础操作就这么一些,更详细的可以查看官方文档。

转载于:https://www.cnblogs.com/zenan/p/11540463.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值