pymongo
provides all the methods of interaction between mongdb and python
Installation method: pip install pymongo
Database and collection can be created automatically
from pymongo import MongoClient
client =MongoClient(host,port) #If it is a local connection host,The port parameter can be omitted
collection = client[db name][Collection name]
# collection = client.db name.Collection name#Same usage as above
from pymongo import MongoClient
from urllib.parse import quote_plus
user ='python' #account number
password ='python' #password
host ='127.0.0.1' # host
port =27017 # port
uri ="mongodb://%s:%s@%s"%(quote_plus(user),quote_plus(password),
host)
# quote_plus function: encode the url
# uri = mongodb://python:[email protected]
client =MongoClient(uri, port=port)
collection = client.db name.Collection name
insert can insert a list of data in batches, or insert a piece of data
collection.insert({A piece of data})
collection.insert([{Data One},{Data two}])
Return the _id of the inserted data
ret = collection.insert({"name":"test10010","age":33})print(ret)
Returns a list of ObjectId objects
item_list =[{"name":"test1000{}".format(i)}for i inrange(10)]
rets = collection.insert(item_list)print(rets)for ret in rets:print(ret)
Receive a condition in dictionary form and return the entire data in dictionary form
If the condition is empty, return the first one
ret = client.test.test.find_one({'name':'test10001'})print(ret) #A dictionary containing the ObjectId objects of mongodb
_ = ret.pop('_id') #Clear the k of the ObjectId object of mongodb,v
print(ret)
Return all results that meet the condition, if the condition is empty, return all
The result is a Cursor cursor object, an iterable object, which can be similar to reading a file pointer, but it can only be read once
rets = collection.find({"name":"test10005"}),
for ret in rets:print(ret)for ret in rets: #There is no content in rets at this time
print(ret)
data ={'msg':'This is a complete piece of data 1','name':'Haha'}
client.test.test.update({'haha':'heihei'},{'$set':data}, upsert=True)
data ={'msg':'This is a complete piece of data 2','name':'Haha'} #The complete data is obtained after querying
client.test.test.update({},{'$set':data}, multi=True, upsert=True)
data ={'msg':'Specify to update msg only___1'}
client.test.test.update({},{'$set':data}, upsert=True)
data ={'msg':'Specify to update msg only___2'}
client.test.test.update({},{'$set':data}, multi=True, upsert=True)
collection.delete_one({"name":"test10010"})
collection.delete_many({"name":"test10010"})
Check pymongo official documentation or source code http://api.mongodb.com/python/current/
Recommended Posts