您的位置:首页 > 编程语言 > Go语言

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()#入参是list

new_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 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mongodb python