MongoDB是由C++语言编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,其内容存储形式类似JSON对象,它的字段值可以包含其他文档、数组及文档数组,非常灵活。在这一节中,我们就来看看Python 3下MongoDB的存储操作。 1. 准备工作在开始之前,请确保已经安装好了MongoDB并启动了其服务,并且安装好了Python的PyMongo库。 2. 连接MongoDB连接MongoDB时,我们需要使用PyMongo库里面的 import pymongo client = pymongo.MongoClient(host='localhost', port=27017) 这样就可以创建MongoDB的连接对象了。 另外, client = MongoClient('mongodb://localhost:27017/') 这也可以达到同样的连接效果。 3. 指定数据库MongoDB中可以建立多个数据库,接下来我们需要指定操作哪个数据库。这里我们以test数据库为例来说明,下一步需要在程序中指定要使用的数据库: db = client.test 这里调用 db = client['test'] 这两种方式是等价的。 4. 指定集合MongoDB的每个数据库又包含许多集合(collection),它们类似于关系型数据库中的表。 下一步需要指定要操作的集合,这里指定一个集合名称为students。与指定数据库类似,指定集合也有两种方式: collection = db.students collection = db['students'] 这样我们便声明了一个 5. 插入数据接下来,便可以插入数据了。对于students这个集合,新建一条学生数据,这条数据以字典形式表示: student = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } 这里指定了学生的学号、姓名、年龄和性别。接下来,直接调用 result = collection.insert(student) print(result) 在MongoDB中,每条数据其实都有一个 运行结果如下: 5932a68615c2606814c91f3d 当然,我们也可以同时插入多条数据,只需要以列表形式传递即可,示例如下: student1 = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } student2 = { 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male' } result = collection.insert([student1, student2]) print(result) 返回结果是对应的 [ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')] 实际上,在PyMongo 3.x版本中,官方已经不推荐使用 student = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } result = collection.insert_one(student) print(result) print(result.inserted_id) 运行结果如下: <pymongo.results.InsertOneResult object at 0x10d68b558> 5932ab0f15c2606f0c1cf6c5 与 对于 student1 = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } student2 = { 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male' } result = collection.insert_many([student1, student2]) print(result) print(result.inserted_ids) 运行结果如下: <pymongo.results.InsertManyResult object at 0x101dea558> [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')] 该方法返回的类型是 6. 查询插入数据后,我们可以利用 result = collection.find_one({'name': 'Mike'}) print(type(result)) print(result) 这里我们查询 <class 'dict'> {'_id': ObjectId('5932a80115c2606a59e8a049'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'} 可以发现,它多了 此外,我们也可以根据 from bson.objectid import ObjectId result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')}) print(result) 其查询结果依然是字典类型,具体如下: {'_id': ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'} 当然,如果查询结果不存在,则会返回 对于多条数据的查询,我们可以使用 results = collection.find({'age': 20}) print(results) for result in results: print(result) 运行结果如下: <pymongo.cursor.Cursor object at 0x1032d5128> {'_id': ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'} {'_id': ObjectId('593278c815c2602678bb2b8d'), 'id': '20170102', 'name': 'Kevin', 'age': 20, 'gender': 'male'} {'_id': ObjectId('593278d815c260269d7645a8'), 'id': '20170103', 'name': 'Harden', 'age': 20, 'gender': 'male'} 返回结果是 如果要查询年龄大于20的数据,则写法如下: results = collection.find({'age': {'$gt': 20}}) 这里查询的条件键值已经不是单纯的数字了,而是一个字典,其键名为比较符号 这里将比较符号归纳为下表。
另外,还可以进行正则匹配查询。例如,查询名字以M开头的学生数据,示例如下: results = collection.find({'name': {'$regex': '^M.*'}}) 这里使用 这里将一些功能符号再归类为下表。
关于这些操作的更详细用法,可以在MongoDB官方文档找到: https://docs./manual/reference/operator/query/。 7. 计数要统计查询结果有多少条数据,可以调用 count = collection.find().count() print(count) 或者统计符合某个条件的数据: count = collection.find({'age': 20}).count() print(count) 运行结果是一个数值,即符合条件的数据条数。 8. 排序排序时,直接调用 results = collection.find().sort('name', pymongo.ASCENDING) print([result['name'] for result in results]) 运行结果如下: ['Harden', 'Jordan', 'Kevin', 'Mark', 'Mike'] 这里我们调用 9. 偏移在某些情况下,我们可能想只取某几个元素,这时可以利用 results = collection.find().sort('name', pymongo.ASCENDING).skip(2) print([result['name'] for result in results]) 运行结果如下: ['Kevin', 'Mark', 'Mike'] 另外,还可以用 results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2) print([result['name'] for result in results]) 运行结果如下: ['Kevin', 'Mark'] 如果不使用 值得注意的是,在数据库数量非常庞大的时候,如千万、亿级别,最好不要使用大的偏移量来查询数据,因为这样很可能导致内存溢出。此时可以使用类似如下操作来查询: from bson.objectid import ObjectId collection.find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}}) 这时需要记录好上次查询的 10. 更新对于数据更新,我们可以使用 condition = {'name': 'Kevin'} student = collection.find_one(condition) student['age'] = 25 result = collection.update(condition, student) print(result) 这里我们要更新 运行结果如下: {'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True} 返回结果是字典形式, 另外,我们也可以使用 result = collection.update(condition, {'$set': student}) 这样可以只更新 另外, condition = {'name': 'Kevin'} student = collection.find_one(condition) student['age'] = 26 result = collection.update_one(condition, {'$set': student}) print(result) print(result.matched_count, result.modified_count) 这里调用了 运行结果如下: <pymongo.results.UpdateResult object at 0x10d17b678> 1 0 我们再看一个例子: condition = {'age': {'$gt': 20}} result = collection.update_one(condition, {'$inc': {'age': 1}}) print(result) print(result.matched_count, result.modified_count) 这里指定查询条件为年龄大于20,然后更新条件为 运行结果如下: <pymongo.results.UpdateResult object at 0x10b8874c8> 1 1 可以看到匹配条数为1条,影响条数也为1条。 如果调用 condition = {'age': {'$gt': 20}} result = collection.update_many(condition, {'$inc': {'age': 1}}) print(result) print(result.matched_count, result.modified_count) 这时匹配条数就不再为1条了,运行结果如下: <pymongo.results.UpdateResult object at 0x10c6384c8> 3 3 可以看到,这时所有匹配到的数据都会被更新。 11. 删除删除操作比较简单,直接调用 result = collection.remove({'name': 'Kevin'}) print(result) 运行结果如下: {'ok': 1, 'n': 1} 另外,这里依然存在两个新的推荐方法—— result = collection.delete_one({'name': 'Kevin'}) print(result) print(result.deleted_count) result = collection.delete_many({'age': {'$lt': 25}}) print(result.deleted_count) 运行结果如下: <pymongo.results.DeleteResult object at 0x10e6ba4c8> 1 4
12. 其他操作另外,PyMongo还提供了一些组合方法,如 另外,还可以对索引进行操作,相关方法有 关于PyMongo的详细用法,可以参见官方文档:http://api./python/current/api/pymongo/collection.html。 另外,还有对数据库和集合本身等的一些操作,这里不再一一讲解,可以参见官方文档:http://api./python/current/api/pymongo/。 本节讲解了使用PyMongo操作MongoDB进行数据增删改查的方法。 |
|