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 -h 127.0.0.1 -d database -c collection --type csv --headerline --file /root/demo.csv
--type:指明要导入的文件格式
--headerline:指明第一行是列名,不需要导入
--file:指明要导入的文件

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

原文地址:https://www.cnblogs.com/zenan/p/11540463.html