This article shares with you the detailed steps and example codes for operating mongodb in Python. Friends in need can refer to it.
1 Import pymongo
from pymongo import MongoClient
2 Connect to the server port number 27017
Connect to MongoDB
To connect to MongoDB we need to use the MongoClient in the PyMongo library. Generally speaking, just pass in the IP and port of MongoDB. The first parameter is the address host, and the second parameter is the port. If the port is not passed, the default is 27017.
conn = MongoClient("localhost") MongoClient(host='127.0.0.1',port=27017)
Three connection database
db = conn.Database name
Connection collection
collection = db[collection_name] or collection = db.collection_name
View all collection names
db.collection_names()
Four Insert Data
(1) Insert one piece of data
db.user.insert({"name":"夏利刚","age":18,"hobby":"学习"})
(2) Insert multiple pieces of data
db.user.insert([{"name":"夏利刚","age":18,"hobby":"学习"},{"name":"xxxoo","age":48,"hobby":"学习"}]
(3) It is recommended to use
insert_one 插入一条数据 insert_many() 插入多条数据
data.inserted_id data.inserted_ids
(1) Query all
#带条件的查询 # data = db.user.find({"name":"周日"}) # print(data) #返回result类似一个迭代器 可以使用 next方法 一个一个 的取出来 # print(next(data)) #取出一条数据
db.user.find_one()
db.user.find({"name":"张三"})
from bson.objectid import ObjectId*#用于ID查询 data = db.user.find({"_id":ObjectId("59a2d304b961661b209f8da1")})
(1){"name":{'$regex':"张"}} (2)import re {'xxx':re.compile('xxx')}
(1) sort sort
data = db.user.find({"age":{"$gt":10}}).sort("age",-1) #年龄 升序 查询 pymongo.ASCENDING --升序 data = db.user.find({"age":{"$gt":10}}).sort("age",1) #年龄 降序 查询 pymongo.DESCENDING --降序
db.user.find().limit(3) data = db.user.find({"age":{"$gt":10}}).sort("age",-1).limit(3)
The update() method is actually a method that is not officially recommended. Here it is also divided into update_one() method and update_many() method. The usage is more strict,
db.user.update({"name":"张三"},{"$set":{"age":25}}) db.user.update({"name":"张三"},{"$inc":{"age":25}})
db.user.update_one({"name":"张三"},{"$set":{"age":99}})
db.user.update_many({"name":"张三"},{"$set":{"age":91}})
collection.remove({"name":"lilei"})
collection.remove()
delete_one()即删除第一条符合条件的数据 collection.delete_one({“name”:“ Kevin”}) delete_many()即删除所有符合条件的数据,返回结果是DeleteResult类型 collection.delete_many({“age”: {$lt:25}})
result.deleted_count
conn.close()
How to operate MongoDB with PHP and simple analysis
The above is the detailed content of 9 steps to operate mongodb with Python. For more information, please follow other related articles on the PHP Chinese website!