Mongodb与pymongo¶

首先启动mongod进程 /path/to/mongod --dbpath db

In [1]:
import pymongo
In [2]:
client = pymongo.MongoClient()
In [3]:
db = client['test']
In [4]:
collection = db['students'] 
In [5]:
collection.drop() # drop the table
In [6]:
collection.insert_one({"id": 123, "name": "zhangsan", "gender": "M", "age": 18})
Out[6]:
<pymongo.results.InsertOneResult at 0x1718f788608>
In [7]:
collection.insert_one({"id": 124, "name": "lisi", "gender": "F", "age": 17})
Out[7]:
<pymongo.results.InsertOneResult at 0x1718f7ac6c8>
In [8]:
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}
In [9]:
collection.update_many({"age": 18}, {"$inc": {"age": 2}})
Out[9]:
<pymongo.results.UpdateResult at 0x1718f79ff88>
In [10]:
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}
In [11]:
collection.insert_one({"abc": 123}) # mongodb 不要求插入记录格式统一
Out[11]:
<pymongo.results.InsertOneResult at 0x1718f7ac508>
In [12]:
collection.delete_one({"abc": 123})
Out[12]:
<pymongo.results.DeleteResult at 0x1718f7aca88>
In [13]:
res = collection.delete_many({"age": {"$exists": True}}) # 根据是否存在字段
In [14]:
res.deleted_count
Out[14]:
2
In [ ]:
 
In [ ]: