Python-MongoDB operation

Python-MongoDB operation


Shell connection mongodb command mongo

$ mongo
MongoDB shell version v3.6.2
connecting to: mongodb://
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


change the data


Query data

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

delete data

Reference: Python-MongoDB Operation-Cloud + Community-Tencent Cloud