原文地址:http://www.mapboxx.cn/article/mongodb/
安装MongoDB
安装教程详见:https://www.runoob.com/mongodb/mongodb-window-install.html
启动mongodb服务命令:
mongod --dbpath C:softwaremongodbdatadb
其中,
dbpath
后面的参数是安装的
mongodb
下面创建的目录路径
连接MongoDB
安装
pymongo
库
pip3 install pymongo
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
另外一种写法
client = pymongo.MongoClient('mongodb://localhost:27017/')
指定数据库
db = client.test
或者:
db = client['test']
指定集合
collection = db.student
操作mongodb
插入数据
student = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
result = collection.insert_one(student)
print(result)
<pymongo.results.InsertOneResult object at 0x00000177658B0408>
同时插入多条数据
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)
<pymongo.results.InsertManyResult object at 0x000001776586FE48>
查询数据
result = collection.find_one({'name':'Mike'})
print(type(result))
print(result)
<class 'dict'>
{'_id': ObjectId('5edf58cc4f42c847b642b755'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
可以发现,它多了 _id 属性,这就是 MongoDB 在插入过程中自动添加的。
此外,我们也可以根据 ObjectId 来查询,此时需要调用 bson 库里面的 objectid:
from bson.objectid import ObjectId
result = collection.find_one({'_id':ObjectId('5edf58cc4f42c847b642b755')}) print(result)
多条数据查询
results = collection.find({'age':20})
for result in results:
print(result)
{'_id': ObjectId('5edf587b4f42c847b642b753'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}
{'_id': ObjectId('5edf58cc4f42c847b642b754'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}
查询年龄大于20的数据
results = collection.find({'age': {'$gt':20}})
for result in results:
print(result)
{'_id': ObjectId('5edf58cc4f42c847b642b755'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
正则匹配
results = collection.find({'name': {'$regex': '^M.*'}})
计数
count = collection.find().count()
print(count)
3
C:UsershgvghAnaconda3libsite-packagesipykernel_launcher.py:1: DeprecationWarning: count is deprecated. Use Collection.count_documents instead.
"""Entry point for launching an IPython kernel.
统计符合某个条件的数据
count = collection.find({'age': 20}).count()
print(count)
2
C:UsershgvghAnaconda3libsite-packagesipykernel_launcher.py:1: DeprecationWarning: count is deprecated. Use Collection.count_documents instead.
"""Entry point for launching an IPython kernel.
排序
results = collection.find().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])
['Jordan', 'Jordan', 'Mike']
这里我们调用 pymongo.ASCENDING 指定升序。如果要降序排列,可以传入 pymongo.DESCENDING。
偏移
在某些情况下,我们可能只需要取某几个元素,这时可以利用 skip 方法偏移几个位置,比如偏移 2,就代表忽略前两个元素,得到第 3 个及以后的元素:
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])
['Mike']
此外,还可以通过limit方法指定要取的结果个数
results = collection.find().sort('name', pymongo.ASCENDING).skip(1).limit(1)
print([result['name'] for result in results])
['Jordan']
值得注意的是,在数据量非常庞大的时候,比如在查询千万、亿级别的数据库时,最好不要使用大的偏移量,因为这样很可能导致内存溢出。
更新
condition = {'name': 'Mike'}
student = collection.find_one(condition)
student['age'] = 28
result = collection.update_one(condition, {'$set': student})
print(result)
print(result.matched_count, result.modified_count)
<pymongo.results.UpdateResult object at 0x0000017765A53988>
1 1
condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)
<pymongo.results.UpdateResult object at 0x0000017765ABAE08>
1 1
这里指定查询条件为年龄大于 20,然后更新条件为 {'$inc': {'age': 1}},表示年龄加 1,执行之后会将第一条符合条件的数据年龄加 1。
如果调用 update_many 方法,则会将所有符合条件的数据都更新,示例如下:
condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)
<pymongo.results.UpdateResult object at 0x0000017765ABA888>
1 1
删除
result = collection.delete_one({'name': 'Mike'})
print(result.deleted_count)
0
其他操作
另外,PyMongo 还提供了一些组合方法,如 find_one_and_delete、find_one_and_replace 和 find_one_and_update,它们分别用于查找后删除、替换和更新操作,其使用方法与上述方法基本一致。
另外,我们还可以对索引进行操作,相关方法有 create_index、create_indexes 和 drop_index 等。
关于 PyMongo 的详细用法,可以参见官方文档:http://api.mongodb.com/python/current/api/pymongo/collection.html。
另外,还有对数据库和集合本身等的一些操作,这里不再一一讲解,可以参见官方文档:http://api.mongodb.com/python/current/api/pymongo/。