Python连接示例
<p>本文主要介绍Python连接示例。</p>
<p> <img src="https://obs-cn-shanghai.ocftcloud.com/pacloud/20202805144016-134949d29da3.png" style="height:26px; margin:0px; width:65px" />:</p>
<p> • pymongo可单击<a href="https://pypi.org/project/pymongo/" target="_blank">下载</a>。</p>
<p> • 官方资料可参考<a href="https://pymongo.readthedocs.io/en/stable/" target="_blank">PyMongo 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 install pymongo</span></p>
</td>
</tr>
</tbody>
</table>
<p>2. 获取 DDS 实例的连接信息。</p>
<p>3. Python安装代码:</p>
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="background-color:#f7f8fa">
<p><span style="font-family:Consolas">import uuid</span></p>
<p><span style="font-family:Consolas">from pymongo import MongoClient</span></p>
<p><span style="font-family:Consolas"> #地址</span></p>
<p><span style="font-family:Consolas">CONN_ADDR1 = 'demotest.mongodb.db.cloud.papub:15923'</span></p>
<p><span style="font-family:Consolas">REPLICAT_SET = 'demotest'</span></p>
<p><span style="font-family:Consolas"> username = 'demouser'</span></p>
<p><span style="font-family:Consolas">password = '123456'</span></p>
<p><span style="font-family:Consolas"> #获取mongoclient</span></p>
<p><span style="font-family:Consolas">client = MongoClient([CONN_ADDR1], replicaSet=REPLICAT_SET)</span></p>
<p><span style="font-family:Consolas"> #授权. 这里的user基于test数据库授权</span></p>
<p><span style="font-family:Consolas">client.admin.authenticate(username, password)</span></p>
<p><span style="font-family:Consolas"> #使用test数据库的collection:testColl做例子, 插入doc, 然后根据DEMO名查找</span></p>
<p><span style="font-family:Consolas">demo_name = 'python-' + str(uuid.uuid1())</span></p>
<p><span style="font-family:Consolas">print 'demo_name:', demo_name</span></p>
<p><span style="font-family:Consolas"> doc = dict(DEMO=demo_name, MESG="Hello ApsaraDB For MongoDB")</span></p>
<p><span style="font-family:Consolas">doc_id = client.test.testColl.insert(doc)</span></p>
<p><span style="font-family:Consolas">print 'doc_id:', doc_id</span></p>
<p><span style="font-family:Consolas"> for d in client.test.testColl.find(dict(DEMO=demo_name)):</span></p>
<p><span style="font-family:Consolas"> print 'find documents:', d</span></p>
</td>
</tr>
</tbody>
</table>
提交成功!非常感谢您的反馈,我们会继续努力做到更好!