Python 3 operation mongodb simple and easy to understand tutorial

Time:2022-5-9

PymongoyespythonAn operation ofMongodbLibrary of.

Let’s briefly list some common operation commands.

Connect database

The linked database needs to provide an address and interface. First, import the package.

from pymongo import MongoClient
conn = MongoClient('localhost',27017)

Of course, you can use the following wording:

conn = MongoClient('mongodb://localhost:27017/')

Create database

mongodbYou do not need to create a database in advance, but use it directly. If it is not found, it will be created automatically.

db = conn.testdb

The above statement will create atestdbDatabase. However, when no data is inserted, the database cannot be seen (not displayed) in the management tool.

insert data

First, let’s insert a piece of data and have a look.

Single record insertion

from pymongo import MongoClient
conn = MongoClient('mongodb://localhost:27017/')
db = conn.testdb
db. Col.insert ({"name": "Yanying", "province": "Jiangsu", "age": 25})

be careful:The core operation in the database will be ignored, and the code in the next operation will be written directly.

pythonNothing happened on the console. That’s what success means. Using the management tool to view the database record does contain a piece of data.

Python 3 operation mongodb simple and easy to understand tutorial

Insert multiple records

MongodbYou can also insert multiple pieces of data at a time

db.col.insert([
    {"name": 'Yanying', 'province': 'Jiangsu', 'age': 25},
    {"name": 'Zhang San','province ':' Zhejiang ','age': 24},
    {"name": 'Zhang San 1','province ':' Zhejiang 1 ','age': 25},
    {"name": 'Zhang San 2', 'province': 'Zhejiang 2', 'age': 26},
    {"name": 'Zhang San 3', 'province': 'Zhejiang 3', 'age': 28},
])

Query data

Let’s query the data just inserted.

single query

We can usefind_one()To query a record.

db.col.find_one()

The above statement can query onemongodbrecord. Extra in the record_idIs the only value automatically generated by mongodb.

{'_id': objectid ('5925351ad92fac3250b9ae3f '),'name':'yanying ',' province ':'jiangsu', 'age': 25}

Let’s insert some more data for the following operations. (tens of thousands of words omitted)

Query all

If we need to query all records, we can usedb.col.find()But what is found is a result resource set.

We can useforTo list all records.

for item in db.col.find():
    print(item)

In this way, all records can be obtained.

{'_id': objectid ('5925351ad92fac3250b9ae3f '),'name':'yanying ',' province ':'jiangsu', 'age': 25}
{'_id': objectid ('592550e5d92fac0b8c449f87 '),' name ':' Zhangsan ',' province ':' Beijing ',' age ': 29}
{'_id': objectid ('592550f6d92fac3548c20b1a '),' name ':' Lisi ',' province ':' Shanghai ',' age ': 22}
{'_id': objectid ('59255118d92fac43dcb1999a '),' name ':' Wang Erma ',' province ':' Guangdong ',' age ': 30}

Condition query

Just insert the query criteria as parameters to filter the data.

for item in db.col.find({'name':"yanying"}):
    print(item)

Query results

{'_id': objectid ('5925351ad92fac3250b9ae3f '),'name':'yanying ',' province ':'jiangsu', 'age': 25}

Of course, you can also query records that are less than a certain value

for item in db.col.find({"age":{"$lt":25}}):
    print(item)

Or records greater than a certain value

for item in db.col.find({"age":{"$gt":25}}):
    print(item)

Statistical query

The above code can count the number of all records

db.col.find().count() // 4

Or add some conditions

db.col.find({"age":{"$gt":25}}).count() //2

According to_ ID query record

_idyesmongodbAutomatically generatedid, whose type isObjectId, you need to convert the type if you want to use it.

python3This method is provided in, but you need to import a library.

from bson.objectid import ObjectId

In this way, it can be used directly_idMake an inquiry.

collection.find_one({'_id':ObjectId('592550e5d92fac0b8c449f87')})

Result sorting

Just put the fields to be sorted intosortThe method is enough,MongodbThe default is ascending

db.col.find().sort("age")

However, you can also add some parameters to change the sorting method. For example, reverse order, but remember to import firstpymongolibrary

import pymongo
db.col.find().sort("UserName",pymongo.DESCENDING)

You can also put him in ascending order, even by default

for item in db.col.find().sort('age',pymongo.ASCENDING):
    print(item)

Update data

Updating data is very simple. You only need one condition and the data to be updated

db. Col. update ({'_id': objectid ('59255118d92fac43dcb1999a ')}, {' $set ': {' name ':' Wang Erma 33333 '})

The results are as follows:Wang ErmaBecomeWang Erma 33333

{'_id': objectid ('59255118d92fac43dcb1999a '),' name ':' Wang Erma 33333 ',' province ':' Guangdong ',' age ': 30}

Delete data

Delete data usageremove()Method. If the method has conditions, delete the specified condition data, otherwise delete all

deletenameIt is the user of Wang Erma 33333.

db. Col. remove ({'name': 'Wang Erma 33333'})

Delete all data(Use with caution

db.col.remove()

Recommended Today

[tree technology headline] Wednesday, April 13, 2022

Conflux community dynamics1. [network status] conflux network computing power ≈ 1.5T, token transfer TPS ≈ 1003, 312k transactions yesterday, 236.283k new accounts and 3 new contracts yesterday.2. [POS parameter] POS has 80m total positions, 130 nodes, 18.3% annual interest rate (theoretical calculation), and 1.36M cumulative interest.3. [Dao vote] conflux dao# 12’s fourth vote on the […]