Module import
from pymongo import MongoClient
Instantiate client and establish connection
client=MongoClient(host="127.0.0.1",port=27017) collection=client["test"]["std "] #test is the database, std is the collection
Insert a piece of data
collection.insert({"name":"xiaoming","age":18})
Insert a piece of data and modify the default _id value.
collection.insert({"_id":20181126,"name":"xiaoming","age":18})
Insert a piece of data, use ret to receive it, and print out the value of _id
ret=collection.insert({"_id":20181126,"name":"xiaoming","age":18}) print(ret) #Run result: 20181126
Insert multiple pieces of data insert_many(),
data_list=[{"name":"test{} ".format(i)} for i in range(10)] collection.insert_many(data_list)
Query a record find_one()
t=collection.find_one({"name":"xiaowang"}) print(t)
To query multiple records find(), the output is a cursor.
t=collection.find({"name":"xiaowang"}) print(t)
Update a piece of data update_one()
collection.update_one({"name":"xiaoming"},{"$set":{"name":"xiaozhang"}})
Update multiple pieces of data update_many()
collection.update_many({"name":"xiaoming"},{"$set":{"name":"xiaozhang"}})
delete_one() to delete a piece of data
collection.delete_one({"name":"xiaowang"})
Delete multiple pieces of data delete_many()
collection.delete_many({"name":"xiaowang"})