pymongo 学习-如何使用
2016-07-11 16:04
405 查看
pymongo 学习-如何使用
(翻译自https://api.mongodb.com/python/current/tutorial.html)
准备
1、安装pymongo,附件是2.7和3.2版,都是64位;2、安装mongodb;
3、安装Python或者在eclipse中安装pyDev;
连接到mongodb
有3种方式(不限于3种,比如连接副本集):from pymongo import MongoClient
1、client = MongoClient()#连接到本地
特殊说明:可能在eclipse中出现不识别汉语,报错的现象,解决方法–#!/usr/bin/env python# -- coding: utf-8 --即可
2、client = MongoClient(‘localhost’, 27017)
3、client = MongoClient(‘mongodb://localhost:27017’)
获取数据库
有2种方式:(假如要连接mydb数据库)1、db = client.mydb
2、db = client[‘mydb’]
* 当mydb不存在时,会自动创建 *
获取集合
有2种方式:(假如要连接mycoll集合)1、coll = db.mycoll
2、db = db[‘mycoll’]
【1】集合相当于MySQL中的表。每个集合包含多个文档,文档相当于MySQL中一行,只不过文档中字段个数可以不同,而MySQL不行。*
【2】当mycoll不存在,会自动创建。注意:mongodb中数据库和集合的自动创建不是立即生效的,是发生在第一次插入数据时,才创建。
文档
数据在mongodb中是以json的格式存储和显示的。其实mongodb底层存储格式是bson,可查看官方文档。
import datetime
post = {“author”: “Mike”,
… “text”: “My first blog post!”,
… “tags”: [“mongodb”, “python”, “pymongo”],
… “date”: datetime.datetime.utcnow()}
读者请注意缩进,第一次用这个编辑器,见谅!
插入文档
posts = db.posts#定位到posts集合,不用操心,是否存在post_id = posts.insert_one(post).inserted_id
print post_id
如果posts集合之前不存在,现在可以查看,是否自动创建了。
db.collection_names(include_system_collections=False)
获取一个文档
1、posts.find_one()2、find_one()还支持条件查询:
posts.find_one({“author”:”Mike”})
#返回所有作者是Mike的第一个文档,没有则返回None。
获取多个文档
find()#用法同find_one(),返回所有符合条件的文档批量插入
1、inset_many()#入参是listnew_posts = [{“author”: “Mike”,
… “text”: “Another post!”,
… “tags”: [“bulk”, “insert”],
… “date”: datetime.datetime(2009, 11, 12, 11, 14)},
… {“author”: “Eliot”,
… “title”: “MongoDB is fun”,
… “text”: “and pretty easy too!”,
… “date”: datetime.datetime(2009, 11, 10, 10, 45)}]
result = posts.insert_many(new_posts)
2、从2.6版以后,出现了专门的批量处理函数bulk(),有两种实现方式:有序和无序。有序:顺序执行,遇到异常终止;无序:返回失败的项。
bulk = db.test.initialize_ordered_bulk_op()
Remove all documents from the previous example.
…bulk.find({}).remove()
bulk.insert({‘_id’: 1})
bulk.insert({‘_id’: 2})
bulk.insert({‘_id’: 3})
bulk.find({‘_id’: 1}).update({‘set’: {‘foo’: ‘bar’}})
bulk.find({‘_id’: 4}).upsert().update({‘inc’: {‘j’: 1}})
bulk.find({‘j’: 1}).replace_one({‘j’: 2})
result = bulk.execute()
注意:以上两种均有限制—批量处理是按分组执行,1000条命令为一组,最多1000个分组,所以在命令超过1000*1000时(如大量数据的备份时)慎用。
计数
1、posts.count()2、psots.find({“author”:”Mike”}).count()
指定范围查询
d = datetime.datetime(2009, 11, 12, 12)for post in posts.find({“date”: {“$lt”: d}}).sort(“author”):
… print post
¥lt:小于,sort函数的参数还可指定按…升序 且/或 按…降序
索引
1、创建索引result = db.profiles.create_index([(‘user_id’, pymongo.ASCENDING)],
… unique=True)
list(db.profiles.index_information())
[u’user_id_1’, u’id‘]
2、插入新数据
user_profiles = [
… {‘user_id’: 211, ‘name’: ‘Luke’},
… {‘user_id’: 212, ‘name’: ‘Ziltoid’}]
result = db.profiles.insert_many(user_profiles)
3、索引值不予许重复
new_profile = {‘user_id’: 213, ‘name’: ‘Drew’}
duplicate_profile = {‘user_id’: 212, ‘name’: ‘Tommy’}
result = db.profiles.insert_one(new_profile) # This is fine.
result = db.profiles.insert_one(duplicate_profile)
Traceback (most recent call last):
pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: test_database.profiles.$user_id_1 dup key: { : 212 }
相关文章推荐
- 分享微信开发Html5轻游戏中的几个坑
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- 如何在 Fedora 上安装 MongoDB 服务器
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- PHP添加yaf xhprof mongodb 同理
- mongodb安装
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- 如何在 Ubuntu 上安装 MongoDB