Python 驱动
官方驱动下载地址:pymongo。
官方驱动文档,请参见 MongoDB Python Drivers。
快速开始
Python 示例代码 1
#!/usr/bin/pythonimport pymongoimport randommongodbUri = 'mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin'client = pymongo.MongoClient(mongodbUri)db = client.somedbdb.user.drop()element_num=10for id in range(element_num):name = random.choice(['R9','cat','owen','lee','J'])sex = random.choice(['male','female'])db.user.insert_one({'id':id, 'name':name, 'sex':sex})content = db.user.find()for i in content:print i
Python 示例代码 2
#!/usr/bin/pythonimport pymongomongodbUri = 'mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin'client = pymongo.MongoClient(mongodbUri)db = client.someonedbinserted_id = db.somecoll.insert_one({"somekey":"yiqihapi"}).inserted_idprint inserted_idfor doc in db.somecoll.find(dict(_id=inserted_id)):print docfor doc in db.somecoll.find({"somekey":"yiqihapi"}):print doc
输出信息,如下所示。
5734431e101e2f6d699b37ef{u'somekey': u'yiqihapi', u'_id': ObjectId('5734431e101e2f6d699b37ef')}{u'somekey': u'yiqihapi', u'_id': ObjectId('5734431e101e2f6d699b37ef')}