pymongo的使用

pymongo的使用

我们在python中用到mongo,一般都用pymongo,下面的代码可以练习pymongo

1.1 安装pymongo

sudo pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pymongo

1.2 pymongo的基操

下面这段代码,演示了基本pymongo的操作:

from pymongo import MongoClient, DESCENDING
from bson import ObjectId


class TestPyMongo():
    def __init__(self):
        print("init...")

    def connect_mongo(self, ip, port, db_name, collection_name):
        '''
        建立mongo db连接(mongodb不需要像mysql那样手动关闭,后台会自动关闭),
        使用指定db的指定collection
        '''
        self.client = MongoClient(ip, port)
        self.collection = self.client[db_name][collection_name]

    def test_insert_one(self):
        '''插入一条记录'''
        ret = self.collection.insert_one({"name":"xiaoxu", "age":20, "gender:":"female"})
        print(ret)

    def test_insert_many(self):
        '''插入多条记录'''
        result = [{"name": "xiao{}".format(i), "age":20+i, "gender":"female"} for i in range(10)]
        ret = self.collection.insert_many(result)
        # ret = self.collection.insert_one({"name":"xiaoxu", "age":20, "gender:":"female"})
        print(ret)

    def test_find_one(self):
        '''查找name=xiao1的数据'''
        ret = self.collection.find_one({"name":"xiao1"})
        print(ret['name'])

    def test_find_many(self):
        '''查找age>25的数据,根据年龄降序排列'''
        ret = self.collection.find({"age":{"$gt":25}}).sort("age", DESCENDING)
        print(ret)
        for item in ret:
            print(item)

    def test_update_one(self):
        '''更新name=xiao2的名字,改成xiaox'''
        ret = self.collection.update_one({"name":"xiao2"}, {"$set":{"name":"xiaox"}})
        print(ret)

    def test_update_many(self):
        '''更新所有name=xiaox的名字,改成xiaohongmao'''
        ret = self.collection.update_many({"name":"xiaox"}, {"$set":{"name":"xiaohongmao"}})
        print(ret)

    def test_remove_one(self):
        '''删除一条_id=指定值的记录'''
        ret = self.collection.delete_one({"_id":ObjectId("6055c073b08467e1effce937")})
        print(ret)

    def test_remove_many(self):
        '''删除多条名字叫xiaoxu的记录'''
        ret = self.collection.delete_many({"name":"xiaoxu"})
        print(ret)

    def test_count(self):
        '''统计name=xiaohongmao人数'''
        ret = self.collection.find({"name":"xiaohongmao"}).count()
        print(ret)

    def test_aggregate_group(self):
        '''统计所有name出现的次数'''
        ret = self.collection.aggregate([{"$group":{"_id":"$name", "counter":{"$sum":1}}}])
        print(ret)
        for item in ret:
            print(item)

    def test_aggregate_group_match(self):
        '''统计所有name出现的次数大于4次的name'''
        ret = self.collection.aggregate([
            {"$group":{"_id":"$name", "counter":{"$sum":1}}},
            {"$match":{"counter":{"$gt":4}}}
        ])
        print(ret)
        for item in ret:
            print(item)

    def test_aggregate_group_match_project(self):
        '''统计所有name出现的次数大于4次的name出现的次数'''
        ret = self.collection.aggregate([
            {"$group":{"_id":"$name", "counter":{"$sum":1}}},
            {"$match":{"counter":{"$gt":4}}},
            {"$project":{"_id":0, "counter":1}}
        ])
        print(ret)
        for item in ret:
            print(item)

    def test_insert_many_data(self):
        '''给集合t3插入1000条数据,每条包含了_id, name,_id 范围0-999,name:py0-py999'''
        new_collection = self.client["test1"]["t3"]
        insert_list = [{"_id":i, "name":"py{}".format(i)} for i in range(1000)]
        new_collection.insert_many(insert_list)

    def test_query_many_data_by_id(self):
        '''
        查询id是100的倍数的文档,并输出
        '''
        new_collection = self.client["test1"]["t3"]
        ret = new_collection.find()
        for item in ret:
            if item["_id"] != 0 and item["_id"] % 100 == 0:
                print(item)

    def test_query_many_data_by_regex(self):
        '''
        监于id是整数,而name和id是同时生成的,跟生成的索引值关联。
        可以用name匹配正则表达式,匹配name包含100的倍数的记录。
        查询id是100的倍数的文档,并输出
        '''
        new_collection = self.client["test1"]["t3"]
        ret = new_collection.find({"name":{"$regex":"^py[1-9][0][0]"}})
        for item in ret:
            print(item)


if __name__ == "__main__":
    py_mongo = TestPyMongo()
    py_mongo.connect_mongo("127.0.0.1", 27017, "test1", "stu")
    # py_mongo.test_insert()
    # py_mongo.test_insert_many()
    # py_mongo.test_find_one()
    # py_mongo.test_find_many()
    # py_mongo.test_update_many()
    # py_mongo.test_remove_many()
    # py_mongo.test_remove_one()
    # py_mongo.test_count()
    # py_mongo.test_aggregate_group()
    # py_mongo.test_aggregate_group_match()
    # py_mongo.test_aggregate_group_match_project()
    # py_mongo.test_insert_many_data()
    # py_mongo.test_query_many_data_by_id()
    py_mongo.test_query_many_data_by_regex()

参考:pymongo官方文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值