


Detailed explanation of the use summary of PyMongo in python
This article mainly introduces the summary of the use of PyMongo in python, and introduces the use of the PyMongo module in detail. It has certain reference value. Those who are interested can learn more
What is PyMongo
PyMongo is a driver program that enables python programs to use the Mongodb database and is written in python.
Environment: Ubuntu 14.04+python2.7+MongoDB 2.4
Go first Download the software package from the official website, click on the address to open the link. After decompressing, enter and use python setup.py install to install
or use pip to install pip -m install pymongo
Create a connection
import pymongo client = pymongo.MongoClient('localhost', 27017)
Or you can do this
import pymongo client = MongoClient('mongodb://localhost:27017/')
db = client.mydb #或者 db = client['mydb']
Connect aggregation
Aggregation is equivalent to a table in relational database
collection = db.my_collection #或者 collection = db['my_collection']
View all aggregation names under the database
db.collection_names()
collection.insert({"key1":"value1","key2","value2"})
Delete all
collection.remove()
Delete by condition
collection.remove({"key1":"value1"})
UpdateRecord
Copy code The code is as follows:
collection.update({"key1": "value1"}, {"$set": {"key2": "value2", "key3": "value3"}})
Query a record: find_one() does not Returns the first record with any parameters. With parameters, search returns according to conditions
collection.find_one() collection.find_one({"key1":"value1"})
Query multiple records: find() returns all records without parameters, and with parameters, search returns according to conditions
collection.find() collection.find({"key1":"value1"})
View multiple records gathered
for item in collection.find(): print item
View the total number of aggregated records
print collection.find().count()
Query result sorting
Sort on a single column
collection.find().sort("key1") # 默认为升序 collection.find().sort("key1", pymongo.ASCENDING) # 升序 collection.find().sort("key1", pymongo.DESCENDING) # 降序
Sort on multiple columns
Copy code The code is as follows:
collection.find().sort([("key1", pymongo.ASCENDING), ("key2", pymongo.DESCENDING)])
Example 1:
#!/usr/bin/env python #coding:utf-8 # Author: --<qingfengkuyu> # Purpose: MongoDB的使用 # Created: 2014/4/14 #32位的版本最多只能存储2.5GB的数据(NoSQLFan:最大文件尺寸为2G,生产环境推荐64位) import pymongo import datetime import random #创建连接 conn = pymongo.Connection('10.11.1.70',27017) #连接数据库 db = conn.study #db = conn['study'] #打印所有聚集名称,连接聚集 print u'所有聚集:',db.collection_names() posts = db.post #posts = db['post'] print posts #插入记录 new_post = {"AccountID":22,"UserName":"libing",'date':datetime.datetime.now()} new_posts = [{"AccountID":22,"UserName":"liuw",'date':datetime.datetime.now()}, {"AccountID":23,"UserName":"urling",'date':datetime.datetime.now()}]#每条记录插入时间都不一样 posts.insert(new_post) #posts.insert(new_posts)#批量插入多条数据 #删除记录 print u'删除指定记录:\n',posts.find_one({"AccountID":22,"UserName":"libing"}) posts.remove({"AccountID":22,"UserName":"libing"}) #修改聚集内的记录 posts.update({"UserName":"urling"},{"$set":{'AccountID':random.randint(20,50)}}) #查询记录,统计记录数量 print u'记录总计为:',posts.count(),posts.find().count() print u'查询单条记录:\n',posts.find_one() print posts.find_one({"UserName":"liuw"}) #查询所有记录 print u'查询多条记录:' #for item in posts.find():#查询全部记录 #for item in posts.find({"UserName":"urling"}):#查询指定记录 #for item in posts.find().sort("UserName"):#查询结果根据UserName排序,默认为升序 #for item in posts.find().sort("UserName",pymongo.ASCENDING):#查询结果根据UserName排序,ASCENDING为升序,DESCENDING为降序 for item in posts.find().sort([("UserName",pymongo.ASCENDING),('date',pymongo.DESCENDING)]):#查询结果根据多列排序 print item #查看查询语句的性能 #posts.create_index([("UserName", pymongo.ASCENDING), ("date", pymongo.DESCENDING)])#加索引 print posts.find().sort([("UserName",pymongo.ASCENDING),('date',pymongo.DESCENDING)]).explain()["cursor"]#未加索引用BasicCursor查询记录 print posts.find().sort([("UserName",pymongo.ASCENDING),('date',pymongo.DESCENDING)]).explain()["nscanned"]#查询语句执行时查询的记录数
The above is the detailed content of Detailed explanation of the use summary of PyMongo in python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
