search
HomeBackend DevelopmentPython Tutorial9 steps to operate mongodb with Python

9 steps to operate mongodb with Python

Jun 04, 2018 am 11:49 AM
mongodbpythonstep

This article shares with you the detailed steps and example codes for operating mongodb in Python. Friends in need can refer to it.

1 Import pymongo

from pymongo import MongoClient

2 Connect to the server port number 27017

Connect to MongoDB

To connect to MongoDB we need to use the MongoClient in the PyMongo library. Generally speaking, just pass in the IP and port of MongoDB. The first parameter is the address host, and the second parameter is the port. If the port is not passed, the default is 27017.

conn = MongoClient("localhost")
MongoClient(host='127.0.0.1',port=27017)

Three connection database

db = conn.Database name

Connection collection

collection = db[collection_name]
or
collection = db.collection_name

View all collection names

db.collection_names()

Four Insert Data
(1) Insert one piece of data

db.user.insert({"name":"夏利刚","age":18,"hobby":"学习"})

(2) Insert multiple pieces of data

db.user.insert([{"name":"夏利刚","age":18,"hobby":"学习"},{"name":"xxxoo","age":48,"hobby":"学习"}]

(3) It is recommended to use

insert_one 插入一条数据
insert_many() 插入多条数据
## on 3.x and above #(4) Return id and use insert_one()

data.inserted_id
data.inserted_ids

五query data

(1) Query all

db.user.find()

#带条件的查询
# data = db.user.find({"name":"周日"})
# print(data) #返回result类似一个迭代器 可以使用 next方法 一个一个 的取出来
# print(next(data)) #取出一条数据

2) Query a

db.user.find_one()

(3) Query with conditions

db.user.find({"name":"张三"})

(4) Query id

from bson.objectid import ObjectId*#用于ID查询
data = db.user.find({"_id":ObjectId("59a2d304b961661b209f8da1")})

(5) Fuzzy query

(1){"name":{'$regex':"张"}}
(2)import re {'xxx':re.compile('xxx')}

Six sort limit count skip

(1) sort sort

age is greater than 10

data = db.user.find({"age":{"$gt":10}}).sort("age",-1) #年龄 升序 查询 pymongo.ASCENDING --升序
data = db.user.find({"age":{"$gt":10}}).sort("age",1) #年龄 降序 查询 pymongo.DESCENDING --降序

(2) limit value

take three pieces of data

db.user.find().limit(3)
data = db.user.find({"age":{"$gt":10}}).sort("age",-1).limit(3)

(3) count The number of statistical data items

db.user.find().count()

(4) skip From which piece of data to start

db.user.find ().skip(2)

seven update modification

The update() method is actually a method that is not officially recommended. Here it is also divided into update_one() method and update_many() method. The usage is more strict,

(1) update()

db.user.update({"name":"张三"},{"$set":{"age":25}})
db.user.update({"name":"张三"},{"$inc":{"age":25}})

(2) update_one() Update the first qualifying data

db.user.update_one({"name":"张三"},{"$set":{"age":99}})

(3) update_many() Update all qualifying data

db.user.update_many({"name":"张三"},{"$set":{"age":91}})

(4) Its return result It is an UpdateResult type, and then call the matched_count and modified_count attributes to get the number of matching data and the number of affected data respectively.

print(result.matched_count, result.modified_count) No

eight remove Delete


The deletion operation is relatively simple. Directly call the remove() method to specify the conditions for deletion. That’s it, all data that meets the conditions will be deleted,

(1) Delete Zhang San

collection.remove({"name":"lilei"})
collection.remove({"name":"lilei"})

(2) Delete all

collection.remove()

(3) There are still two new recommended methods, delete_one() and delete_many() methods. The examples are as follows:

delete_one()即删除第一条符合条件的数据
collection.delete_one({“name”:“ Kevin”})
delete_many()即删除所有符合条件的数据,返回结果是DeleteResult类型
collection.delete_many({“age”: {$lt:25}})

(4) You can call the deleted_count attribute to get the deleted data strips number.

result.deleted_count

Nine close connections

conn.close()

Related recommendations:

How to operate MongoDB with PHP and simple analysis

The above is the detailed content of 9 steps to operate mongodb with Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.