Summary of python's PyMongo usage

  • 2020-06-01 10:16:17
  • OfStack

What is PyMongo

PyMongo is the driver that enables the python program to use the Mongodb database, written using python.

The installation

Environment: Ubuntu 14.04+ python2.7 +MongoDB 2.4

Go to the official website to download the package, and click the link to open the address. Unzipped and entered, installed using python setup.py install

Or install pip-m install pymongo with pip

The basic use

Create a connection


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

Or you could do this


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

Connect to database


db = client.mydb 
# or 
db = client['mydb'] 

The connection to gather

Aggregation is the equivalent of a table in a relational database


collection = db.my_collection 
# or 
collection = db['my_collection'] 

View all aggregation names under the database


db.collection_names() 

Insert records


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

Delete records

Delete all


collection.remove() 

Conditional deletion


collection.remove({"key1":"value1"}) 

Update record


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

Query log

Query 1 record: find_one() returns the first record without any parameters. Returns a conditional lookup with a parameter


collection.find_one() 
collection.find_one({"key1":"value1"}) 

Query multiple records: find() returns all records without parameters, and returns them by conditional search with parameters


collection.find() 
collection.find({"key1":"value1"}) 

View multiple records gathered


import pymongo 
client = MongoClient('mongodb://localhost:27017/') 
0

View the total number of clustered records


import pymongo 
client = MongoClient('mongodb://localhost:27017/') 
1

Query result sorting

Sort on a single column


import pymongo 
client = MongoClient('mongodb://localhost:27017/') 
2

Sort on multiple columns


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

Example 1:


#!/usr/bin/env python
#coding:utf-8
# Author:  --<qingfengkuyu>
# Purpose: MongoDB The use of 
# Created: 2014/4/14
#32 A version of a bit can only be stored at most 2.5GB The data ( NoSQLFan : the maximum file size is 2G , recommended production environment 64 A) 
 
import pymongo
import datetime
import random
 
# Create a connection 
conn = pymongo.Connection('10.11.1.70',27017)
# Connect to database 
db = conn.study
#db = conn['study']
 
# Print all aggregation names and join the aggregation 
print u' All gathered :',db.collection_names()
posts = db.post
#posts = db['post']
print posts
 
# Insert records 
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()}]# Each record is inserted at a different time 1 sample 
 
posts.insert(new_post)
#posts.insert(new_posts)# Batch insert multiple pieces of data 
 
# Delete records 
print u' Delete specified record :\n',posts.find_one({"AccountID":22,"UserName":"libing"})
posts.remove({"AccountID":22,"UserName":"libing"})
 
# Modify the records in the aggregation 
posts.update({"UserName":"urling"},{"$set":{'AccountID':random.randint(20,50)}})
 
# Query records and count the number of records 
print u' The total record is: ',posts.count(),posts.find().count()
print u' Query a single record :\n',posts.find_one()
print posts.find_one({"UserName":"liuw"})
 
# Query all records 
print u' Query multiple records :'
#for item in posts.find():# Query all records 
#for item in posts.find({"UserName":"urling"}):# Query specified record 
#for item in posts.find().sort("UserName"):# Query results based on UserName Sort, by default, in ascending order 
#for item in posts.find().sort("UserName",pymongo.ASCENDING):# Query results based on UserName Sorting, ASCENDING For the ascending ,DESCENDING For the descending order 
for item in posts.find().sort([("UserName",pymongo.ASCENDING),('date',pymongo.DESCENDING)]):# Query results are sorted by multiple columns 
  print item
 
# View the performance of query statements 
#posts.create_index([("UserName", pymongo.ASCENDING), ("date", pymongo.DESCENDING)])# indexed 
print posts.find().sort([("UserName",pymongo.ASCENDING),('date',pymongo.DESCENDING)]).explain()["cursor"]# Not indexed BasicCursor Query log 
print posts.find().sort([("UserName",pymongo.ASCENDING),('date',pymongo.DESCENDING)]).explain()["nscanned"]# The number of records queried when the query statement is executed 

Related articles: