Python-MongoDB operation

Python-MongoDB operation

pymogo

Shell connection mongodb command mongo

$ mongo
MongoDB shell version v3.6.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.2
Server has startup warnings:
2018-08-05T14:29:13.960+0800 I CONTROL [initandlisten]
2018-08-05T14:29:13.960+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2018-08-05T14:29:13.960+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2018-08-05T14:29:13.960+0800 I CONTROL [initandlisten]

Connect mongo

Connect to local mongo by default

from pymongo import MongoClient
client =MongoClient()

Connect mongo in parameter form

client = MongoClient(host='IP', port=27017) #The port number defaults to 27017 which is a numeric value

Connect mongo in URI form

client = MongoClient('mongodb://IP:27017')

Create a database

#Create database, two ways
db = client.peopleinfo    
db = client['peopleinfo']  

Connect to pydb database

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)
db = client['pydb']

Create data table

Like the database, the following two methods are available

t = db.stu
t = db['stu']

Insert data

stu.insert({'_id':3,'name':'mog','age':20})

change the data

stu.update({'_id':3},{'$set':{'name':'mongo'}})

Query data

for cur in stu.find({'age':{'$gte':20}}):
    print(cur)

delete data

stu.delete_one({'_id':'2'})
Reference: https://cloud.tencent.com/developer/article/1437124 Python-MongoDB Operation-Cloud + Community-Tencent Cloud