Home > Backend Development > Python Tutorial > Detailed explanation of the use summary of PyMongo in python

Detailed explanation of the use summary of PyMongo in python

黄舟
Release: 2017-05-28 10:57:54
Original
2713 people have browsed it

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.

Installation

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

Basic use

Create a connection

import pymongo 
client = pymongo.MongoClient('localhost', 27017)
Copy after login

Or you can do this

import pymongo 
client = MongoClient('mongodb://localhost:27017/')
Copy after login

Connect database

db = client.mydb 
#或者
db = client['mydb']
Copy after login

Connect aggregation

Aggregation is equivalent to a table in relational database

collection = db.my_collection 
#或者
collection = db['my_collection']
Copy after login

View all aggregation names under the database

db.collection_names()
Copy after login

Insert record

collection.insert({"key1":"value1","key2","value2"})
Copy after login

Delete record

Delete all

collection.remove()
Copy after login

Delete by condition

collection.remove({"key1":"value1"})
Copy after login

UpdateRecord

Copy code The code is as follows:

collection.update({"key1": "value1"}, {"$set": {"key2": "value2", "key3": "value3"}})
Copy after login

Query records

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"})
Copy after login

Query multiple records: find() returns all records without parameters, and with parameters, search returns according to conditions

collection.find() 
collection.find({"key1":"value1"})
Copy after login

View multiple records gathered

for item in collection.find():   
  print item
Copy after login

View the total number of aggregated records

print collection.find().count()
Copy after login

Query result sorting

Sort on a single column

collection.find().sort("key1") # 默认为升序 
collection.find().sort("key1", pymongo.ASCENDING) # 升序 
collection.find().sort("key1", pymongo.DESCENDING) # 降序
Copy after login

Sort on multiple columns

Copy code The code is as follows:

collection.find().sort([("key1", pymongo.ASCENDING), ("key2", pymongo.DESCENDING)])
Copy after login

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(&#39;10.11.1.70&#39;,27017)
#连接数据库
db = conn.study
#db = conn[&#39;study&#39;]
 
#打印所有聚集名称,连接聚集
print u&#39;所有聚集:&#39;,db.collection_names()
posts = db.post
#posts = db[&#39;post&#39;]
print posts
 
#插入记录
new_post = {"AccountID":22,"UserName":"libing",&#39;date&#39;:datetime.datetime.now()}
new_posts = [{"AccountID":22,"UserName":"liuw",&#39;date&#39;:datetime.datetime.now()},
       {"AccountID":23,"UserName":"urling",&#39;date&#39;:datetime.datetime.now()}]#每条记录插入时间都不一样
 
posts.insert(new_post)
#posts.insert(new_posts)#批量插入多条数据
 
#删除记录
print u&#39;删除指定记录:\n&#39;,posts.find_one({"AccountID":22,"UserName":"libing"})
posts.remove({"AccountID":22,"UserName":"libing"})
 
#修改聚集内的记录
posts.update({"UserName":"urling"},{"$set":{&#39;AccountID&#39;:random.randint(20,50)}})
 
#查询记录,统计记录数量
print u&#39;记录总计为:&#39;,posts.count(),posts.find().count()
print u&#39;查询单条记录:\n&#39;,posts.find_one()
print posts.find_one({"UserName":"liuw"})
 
#查询所有记录
print u&#39;查询多条记录:&#39;
#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),(&#39;date&#39;,pymongo.DESCENDING)]):#查询结果根据多列排序
  print item
 
#查看查询语句的性能
#posts.create_index([("UserName", pymongo.ASCENDING), ("date", pymongo.DESCENDING)])#加索引
print posts.find().sort([("UserName",pymongo.ASCENDING),(&#39;date&#39;,pymongo.DESCENDING)]).explain()["cursor"]#未加索引用BasicCursor查询记录
print posts.find().sort([("UserName",pymongo.ASCENDING),(&#39;date&#39;,pymongo.DESCENDING)]).explain()["nscanned"]#查询语句执行时查询的记录数
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template