Python连接示例

<p>本文主要介绍Python连接示例。</p> <p>&nbsp; &nbsp;&nbsp;<img src="https://pcp-portal-sca.obs-cn-shenzhen.pinganyun.com/pcp-portal-sca/20202805102426-10eeabb09ab2.png" style="height:26px; margin:0px; width:65px" />:</p> <p>&nbsp; &nbsp;&nbsp;&bull;&nbsp; &nbsp;pymongo可单击<a href="https://pypi.org/project/pymongo/" target="_blank">下载</a>。</p> <p>&nbsp; &nbsp;&nbsp;&bull;&nbsp; &nbsp;官方资料可参考<a href="https://pymongo.readthedocs.io/en/stable/" target="_blank">PyMongo&nbsp;Documentation</a>。</p> <p><span style="font-size:18px"><strong>操作步骤</strong></span></p> <p>1. 执行以下命令,安装pymongo。</p> <table border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td style="background-color:#f7f8fa"> <p><span style="font-family:Consolas">pip <strong>install</strong> pymongo</span></p> </td> </tr> </tbody> </table> <p>2.&nbsp; 获取 DDS 实例的连接信息。</p> <p>3.&nbsp; Python安装代码:</p> <table border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td style="background-color:#f7f8fa"> <p><span style="font-family:Consolas"><strong>import</strong> uuid</span></p> <p><span style="font-family:Consolas"><strong>from</strong> pymongo <strong>import</strong> MongoClient</span></p> <p><span style="font-family:Consolas">&nbsp;#地址</span></p> <p><span style="font-family:Consolas">CONN_ADDR1 = &#39;demotest.mongodb.db.cloud.papub:15923&#39;</span></p> <p><span style="font-family:Consolas">REPLICAT_SET = &#39;demotest&#39;</span></p> <p><span style="font-family:Consolas">&nbsp;username = &#39;demouser&#39;</span></p> <p><span style="font-family:Consolas">password = &#39;123456&#39;</span></p> <p><span style="font-family:Consolas">&nbsp;#获取mongoclient</span></p> <p><span style="font-family:Consolas">client = MongoClient([CONN_ADDR1], replicaSet=REPLICAT_SET)</span></p> <p><span style="font-family:Consolas">&nbsp;#授权. 这里的user基于test数据库授权</span></p> <p><span style="font-family:Consolas">client.admin.authenticate(username, password)</span></p> <p><span style="font-family:Consolas">&nbsp;#使用test数据库的collection:testColl做例子, 插入doc, 然后根据DEMO名查找</span></p> <p><span style="font-family:Consolas">demo_name = &#39;python-&#39; + str(uuid.uuid1())</span></p> <p><span style="font-family:Consolas"><strong>print</strong> &#39;demo_name:&#39;, demo_name</span></p> <p><span style="font-family:Consolas">&nbsp;doc = dict(DEMO=demo_name, MESG=&quot;Hello ApsaraDB For MongoDB&quot;)</span></p> <p><span style="font-family:Consolas">doc_id = client.test.testColl.insert(doc)</span></p> <p><span style="font-family:Consolas"><strong>print</strong> &#39;doc_id:&#39;, doc_id</span></p> <p><span style="font-family:Consolas">&nbsp;<strong>for</strong> d <strong>in</strong> client.test.testColl.find(dict(DEMO=demo_name)):</span></p> <p><span style="font-family:Consolas">&nbsp;&nbsp;&nbsp; <strong>print</strong> &#39;find documents:&#39;, d</span></p> </td> </tr> </tbody> </table>
以上内容是否解决了您的问题?
请补全提交信息!
咨询·建议

电话咨询

400-151-8800

邮件咨询

cloud@pingan.com

在线客服

工单支持

解决云产品相关技术问题