MongoDB的学习详见 官方文档 或者 我的博客
运行环境: + Pymongo 3.7.2
准备工作
1 2 3 4 5 6 7 8 9 10 11 12
| import pymongo
client = pymongo.MongoClient('localhost',27017)
db = client.dbname db = client['dbname']
collection = db.collectionname collection = db['collectionname']
|
一、添加记录Create
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
student1 = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } student2 = { 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male' }
result = collection.insert_one(student1) print(result)
print(result.inserted_id)
result = collection.insert_many([student1, student2]) print(result)
print(result.inserted_ids)
|
二、查找记录Find
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
result = collection.find_one({'name': 'Mike'}) print(type(result))
print(result)
results = collection.find({'age': 20}) print(results)
for result in results: print(result) """ {'_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'} """
|
还有一些其他函数如下
1 2 3 4 5 6 7 8
| count = collection.find().count()
results = collection.find().sort('name',pymongo.ASCENDING)
results = collection.find().sort('name',pymongo.ASCENDING).skip(2)
results = collection.find().sort('name',pymongo.ASCENDING).skip(2).limit(2)
|
三、更新记录Update
1 2 3 4 5 6 7 8 9 10 11
|
condition = {'age': {'$gt': 20}} result = collection.update_many(condition, {'$inc': {'age': 1}}) print(result)
print(result.matched_count, result.modified_count)
|
四、删除记录Remove
参考链接:
- https://www.jb51.net/article/119823.htm
- http://api.mongodb.com/python/current/api/pymongo/collection.html