PyMongo安装使用笔记
这里是简单的安装和使用记录,首先要有一个可用的mongo环境,win环境或者linux环境都可以。 假定你对mongo有所了解和知道一些命令行操作。
安装和更新
跟大多数py包安装一样,可以源码安装,也可以使用pip或者easy_install来安装
安装
代码如下:
pip install pymongo
升级
代码如下:
pip install --upgrade pymongo
其他安装方法请参照文档pymongo安装
操作
官网教程
小案例
代码如下:
#-*- coding: utf-8 -*-
#python2.7x
#author: orangleliu @2014-09-24
'''
pymongo的简单使用
'''
from pymongo import MongoClient
def get_db():
#建立连接
client = MongoClient("localhost", 27017)
#test,还有其他写法
db = client.test
return db
def get_collection(db):
#选择集合(mongo中collection和database都是lazy创建的,具体可以google下)
collection = db['posts']
print collection
def insert_one_doc(db):
#插入一个document
posts = db.posts
post = {"name":"lzz", "age":25, "weight":"55"}
post_id = posts.insert(post)
print post_id
def insert_mulit_docs(db):
#批量插入documents,插入一个数组
posts = db.posts
post = [ {"name":"nine", "age":28, "weight":"55"},
{"name":"jack", "age":25, "weight":"55"}]
obj_ids = posts.insert(post)
print obj_ids
##查询,可以对整个集合查询,可以根ObjectId查询,可以根据某个字段查询等
def get_all_colls(db):
#获得一个数据库中的所有集合名称
print db.collection_names()
def get_one_doc(db):
#有就返回一个,没有就返回None
posts = db.posts
print posts.find_one()
print posts.find_one({"name":"jack"})
print posts.find_one({"name":"None"})
return
def get_one_by_id(db):
#通过objectid来查找一个doc
posts = db.posts
obj = posts.find_one()
obj_id = obj["_id"]
print "_id 为ObjectId类型 :"
print posts.find_one({"_id":obj_id})
#需要注意这里的obj_id是一个对象,不是一个str,使用str类型作为_id的值无法找到记录
print "_id 为str类型 "
print posts.find_one({"_id":str(obj_id)})
#可以通过ObjectId方法把str转成ObjectId类型
from bson.objectid import ObjectId
print "_id 转换成ObjectId类型"
print posts.find_one({"_id":ObjectId(str(obj_id))})
def get_many_docs(db):
#mongo中提供了过滤查找的方法,可以通过各
#种条件筛选来获取数据集,还可以对数据进行计数,排序等处理
posts = db.posts
#所有数据,按年龄排序, -1是倒序
all = posts.find().sort("age", -1)
count = posts.count()
print "集合中所有数据 %s个"%int(count)
for i in all:
print i
#条件查询
count = posts.find({"name":"lzz"}).count()
print "lzz: %s"%count
for i in posts.find({"name":"lzz", "age":{"$lt":20}}):
print i
def clear_coll_datas(db):
#清空一个集合中的所有数据
db.posts.remove({})
if __name__ == "__main__":
db = get_db()
obj_id = insert_one_doc(db)
obj_ids = insert_mulit_docs(db)
#get_all_colls(db)
#get_one_doc(db)
#get_one_by_id(db)
#get_many_docs(db)
clear_coll_datas(db)
这都是写简单的操作,至于集合操作,group操作等以后在总结。

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

AI Hentai Generator
Generate AI Hentai for free.

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

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge
