pymongo 批操作

为什么要进行批操作?

答:单条mongo操作很多时间都花费在网络延迟上了,批操作减少了网络操作的次数,整体性能大大挺高了。

文档来源在哪?

答:pymongo 官网https://api.mongodb.com/python/current/examples/bulk.html

mongo 有没有批量查询?

答:mongo 没有批量查询,需要自己查出来后再判断;不能批量执行查询语句。

mongo 批量操作示例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import sys
from pprint import pprint

from pymongo import MongoClient
from pymongo import InsertOne, DeleteOne, ReplaceOne
from pymongo.errors import BulkWriteError
from pymongo import bulk

def test_bulk_write():
    """
    Breifs:
        test bulk_write
    """
    client = MongoClient('45.77.10.62', 27017)
    db = client.news
    requests = [\
        ReplaceOne({'j': 2}, {'i': 5}),\
        InsertOne({'_id': 5}), \
        DeleteOne({'i': 5})\
        ]
    try:
        db.test.bulk_write(requests, ordered=True)
    except BulkWriteError as bwe:
        pprint(bwe.details)

def test_bulk():
    """
    test bulk
    """
    client = MongoClient('45.77.10.62', 27017)
    collection = client.news.test
    operate = bulk.BulkOperationBuilder(collection, ordered = True)
    operate.insert({'test':'12321', '_id': 123})
    operate.insert({'test':'12321', '_id': 124})
    operate.execute()

if __name__ == '__main__':
    test_bulk_write()
    test_bulk()
View Code

 

posted @ 2018-07-27 14:32  YoZane  阅读(192)  评论(0编辑  收藏  举报