首先启动mongod进程 /path/to/mongod --dbpath db
import pymongo
client = pymongo.MongoClient()
db = client['test']
collection = db['students']
collection.drop() # drop the table
collection.insert_one({"id": 123, "name": "zhangsan", "gender": "M", "age": 18})
<pymongo.results.InsertOneResult at 0x1718f788608>
collection.insert_one({"id": 124, "name": "lisi", "gender": "F", "age": 17})
<pymongo.results.InsertOneResult at 0x1718f7ac6c8>
for item in collection.find():
print(item)
{'_id': ObjectId('5e07e52dee1e0dc4de9a0978'), 'id': 123, 'name': 'zhangsan', 'gender': 'M', 'age': 18} {'_id': ObjectId('5e07e52dee1e0dc4de9a0979'), 'id': 124, 'name': 'lisi', 'gender': 'F', 'age': 17}
collection.update_many({"age": 18}, {"$inc": {"age": 2}})
<pymongo.results.UpdateResult at 0x1718f79ff88>
for item in collection.find():
print(item)
{'_id': ObjectId('5e07e52dee1e0dc4de9a0978'), 'id': 123, 'name': 'zhangsan', 'gender': 'M', 'age': 20} {'_id': ObjectId('5e07e52dee1e0dc4de9a0979'), 'id': 124, 'name': 'lisi', 'gender': 'F', 'age': 17}
collection.insert_one({"abc": 123}) # mongodb 不要求插入记录格式统一
<pymongo.results.InsertOneResult at 0x1718f7ac508>
collection.delete_one({"abc": 123})
<pymongo.results.DeleteResult at 0x1718f7aca88>
res = collection.delete_many({"age": {"$exists": True}}) # 根据是否存在字段
res.deleted_count
2