Python connection MONGO database is mainly used Pymongo connection, the general situation is divided into two kinds of connection, one through the specified port and address directly connected, and another through the format of the URI connection
1. Connect MONGO by specifying port and address
conn = Mongoclient ("47.93.194.180", 27017= conn.coder = Db.users #连接到users集合 print(Table.count ()) #统计集合中的数据
2. Connect via URI
from Import 'mongodb://%s:%s' % ("47.93.194.180", 27017 = Mongoclient (Mango_uri) # Create link db = Conn.coder # Connection Coder Database table = db.users # Select the Users collection print(Table.count ()) # Count collection data rows
Attention:
The current connection mode belongs to the MONGO database does not have a password, the general MONGO will set the password, because not set the password is easy to be black, if you set the password, through the URI connection need to encode the password, if not encoded will prompt " Pymongo.errors.InvalidURI: ': ' or ' @ ' characters in a username or password must is escaped according to RFC 2396 ";
Mongo password is for the database, so after setting the password we need to connect the database Direct Authentication connection mode is as follows
fromUrllibImportParse fromPymongoImportmongoclientpasswd="[email protected]"passwd= Parse.quote (passwd)#encode the password firstMango_uri ='Mongodb://%s:%[email protected]%s:%s/%s'% ("SA", passwd,"47.93.194.180","27030","mapdb")#You need to specify a database when linkingconn = Mongoclient (Mango_uri)#Create a linkdb = conn.mapdb#connecting the Coder databaseTable = Db.bike#Select the Users collectionPrint(Table.count ())#Count collection data rows
There are two ways to connect a Pymongo database and a collection of connections
1. Connect the database and the collection through the "." directly referencing databases and collections
db = conn.mapdb # connection coder database table = db.bike # Select the Users collection
2. Connecting databases and collections referencing databases and collections through "[Name]"
db = conn["mapdb"] # connection coder database table = db[" Bike"] # Select Users Collection
Attention:
The first type of connection cannot set the name of the database and collection to a variable, but the latter can be set;
Python Connection MONGO Database