这里是简单的安装和使用记录,首先要有一个可用的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操作等以后在总结。

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

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

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti


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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

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