tencent cloud


Sample of Reading and Writing Data in MongoDB Instance

Last updated: 2020-05-25 14:31:28

This document uses Python sample code to demonstrate the basic data read/write operations in a TencentDB for MongoDB sharded cluster. Create a sharded cluster instance in the console first and then add the following codes in the service:

Sample code:

import pymongo
import random

mongodbUri = 'mongodb://mongouser:1234567a@'

client = pymongo.MongoClient(mongodbUri)
db = client.test

if 'num' in db.collection_names():

#create database and shardkey,shardkey is name
db_admin.command('enableSharding', 'test')
db_admin.command('shardCollection', 'test.num', key = {'name':1})

#insert data
print 'insert docs'
db.num.insert_one({'id':1, 'name':'R9', 'des':'pretty'})
db.num.insert_one({'id':2, 'name':'BOY', 'des':'handsome'})
db.num.insert_one({'id':3, 'name':'cat', 'des':'nice'})
db.num.insert_one({'id':4, 'name':'dog', 'des':'clever'})
print 'list all docs'
for i in db.num.find(): print i

#insert update doc
print 'update R9 and delete BOY'
db.num.update_one({"id":3}, {"$set":{"des":"kind"}})

print 'print R9'
for i in db.num.find({"name":"R9"}): print i
print 'list all docs'
for i in db.num.find(): print i

Execution result:

Contact Us

Contact our sales team or business advisors to help your business.

Technical Support

Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

7x24 Phone Support