pymongo 是 mongodb 的 python Driver Editor.
记录下学习过程中感觉以后会常用多一些部分,以做参考。

1. 连接数据库

要使用pymongo最先应该做的事就是先连上运行中的 mongod 。

  • 创建一个 .py 文件,首先导入 pymongo:

    from pymongo import MongoClient
  • 创建一个连接到 mongod 到客户端:

    client = MongoClient()
    或者:
    client = MongoClient("mongodb://mongodb0.example.net:27019")
  • 连接数据库:

    # 假设要连接的数据库名为 primer
    db = client.primer
    或者:
    db = client['primer']
  • 连接到对应的数据集:

    coll = db.dataset
    coll = db['dataset']

至此,已经完整对连接了数据库和数据集,完成了初识化的操作。

2. 插入数据

insert_one(document)
insert_many(documents, ordered=True)

  • insert_one(document)
    在 pymongo 中的插入函数并不像 mongo shell 中完全一样,所以需要注意一下:

    from datetime import datetime
    result = db.restaurants.insert_one(
    {
    "address": {
    "street": "2 Avenue",
    "zipcode": "10075",
    "building": "1480",
    "coord": [-73.9557413, 40.7720266]
    },
    "borough": "Manhattan",
    "cuisine": "Italian",
    "grades": [
    {
    "date": datetime.strptime("2014-10-01", "%Y-%m-%d"),
    "grade": "A",
    "score": 11
    },
    {
    "date": datetime.strptime("2014-01-16", "%Y-%m-%d"),
    "grade": "B",
    "score": 17
    }
    ],
    "name": "Vella",
    "restaurant_id": "41704620"
    }
    )

其中返回的结果:result 中是一个:InsertOneResult 类:
class pymongo.results.InsertOneResult(inserted_id, acknowledged)
其中 inserted_id 是插入的元素多 _id 值。

  • insert_many(documents, ordered=True)

    result = db.test.insert_many([{'x': i} for i in range(2)])

查询数据

find(filter=None, projection=None, skip=0, limit=0,
no_cursor_timeout=False, cursor_type=CursorType.NON_TAILABLE,
sort=None, allow_partial_results=False, oplog_replay=False,
modifiers=None, manipulate=True)
find_one(filter_or_id=None, *args, **kwargs)

  • find
    find 查询出来的是一个列表集合。

    cursor = db.restaurants.find()
    for document in cursor:
    print(document)
    # 查询字段是最上层的
    cursor = db.restaurants.find({"borough": "Manhattan"})
    # 查询字段在内层嵌套中
    cursor = db.restaurants.find({"address.zipcode": "10075"})
  • 操作符查询

    cursor = db.restaurants.find({"grades.score": {"$gt": 30}})
    cursor = db.restaurants.find({"grades.score": {"$lt": 10}})
    # AND
    cursor = db.restaurants.find({"cuisine": "Italian", "address.zipcode": "10075"})
    cursor = db.restaurants.find(
    {"$or": [{"cuisine": "Italian"}, {"address.zipcode": "10075"}]})
  • find_one
    返回的是一个JSON式文档,所以可以直接使用!

  • sort
    排序时要特别注意,使用的并不是和mongo shell的一样,而是使用了列表,
    当排序的标准只有一个,且是递增时,可以直接写在函数参数中:

    pymongo.ASCENDING = 1
    pymongo.DESCENDING = -1
    cursor = db.restaurants.find().sort("borough")
    cursor = db.restaurants.find().sort([
    ("borough", pymongo.ASCENDING),
    ("address.zipcode", pymongo.DESCENDING)
    ])

更新文档

更新文档的函数有三个(不能更新 _id 字段)

update_one(filter, update, upsert=False)
update_many(filter, update, upsert=False)
replace_one(filter, replacement, upsert=False)
find_one_and_update(filter, update, projection=None, sort=None, return_document=ReturnDocument.BEFORE, **kwargs)

  • update_one
    返回结果是一个:UpdateResult,如果查找到多个匹配,则只更新
    第一个!

    result = db.restaurants.update_one(
    {"name": "Juni"},
    {
    "$set": {
    "cuisine": "American (New)"
    },
    "$currentDate": {"lastModified": True}
    }
    )
    result.matched_count
    10
    result.modified_count
    1
  • update_many
    查找到多少匹配,就更新多少。

    result = db.restaurants.update_many(
    {"address.zipcode": "10016", "cuisine": "Other"},
    {
    "$set": {"cuisine": "Category To Be Determined"},
    "$currentDate": {"lastModified": True}
    }
    )
    result.matched_count
    20
    result.modified_count
    20
  • replace_one

    result = db.restaurants.replace_one(
    {"restaurant_id": "41704620"},
    {
    "name": "Vella 2",
    "address": {
    "coord": [-73.9557413, 40.7720266],
    "building": "1480",
    "street": "2 Avenue",
    "zipcode": "10075"
    }
    }
    )
    result.matched_count
    1
    result.modified_count
    1
  • find_one_and_update
    返回更新前的文档

    db.test.find_one_and_update(
    {'_id': 665}, {'$inc': {'count': 1}, '$set': {'done': True}})
    {u'_id': 665, u'done': False, u'count': 25}}

删除文档

删除时主要有两个:

delete_one(filter)
delete_many(filter)
drop()
find_one_and_delete(filter, projection=None, sort=None, kwargs)
find_one_and_replace(filter, replacement, projection=None, sort=None, return_document=ReturnDocument.BEFORE,
kwargs)

  • delete_one

    result = db.test.delete_one({'x': 1})
    result.deleted_count
    1
  • delete_many

    result = db.restaurants.delete_many({"borough": "Manhattan"})
    result.deleted_count
    10259
    # 删除全部
    result = db.restaurants.delete_many({})
  • drop()
    删除整个集合,是drop_collection()的别名

    db.restaurants.drop()
  • find_one_and_delete

    db.test.count({'x': 1})
    2
    db.test.find_one_and_delete({'x': 1})
    {u'x': 1, u'_id': ObjectId('54f4e12bfba5220aa4d6dee8')}
    db.test.count({'x': 1})
  • find_one_and_replace

    >>> for doc in db.test.find({}):
    ... print(doc)
    ...
    {u'x': 1, u'_id': 0}
    {u'x': 1, u'_id': 1}
    {u'x': 1, u'_id': 2}
    >>> db.test.find_one_and_replace({'x': 1}, {'y': 1})
    {u'x': 1, u'_id': 0}
    >>> for doc in db.test.find({}):
    ... print(doc)
    ...
    {u'y': 1, u'_id': 0}
    {u'x': 1, u'_id': 1}
    {u'x': 1, u'_id': 2}

索引操作

索引主要有创建索引和删除索引:

create_index(keys, **kwargs)
create_indexes(indexes)
drop_index(index_or_name)
drop_indexes()
reindex()
list_indexes()
index_information()

  • create_index

    my_collection.create_index("mike")
    my_collection.create_index([("mike", pymongo.DESCENDING),
    ... ("eliot", pymongo.ASCENDING)])
    my_collection.create_index([("mike", pymongo.DESCENDING)],
    ... background=True)
  • create_indexes

    >>> from pymongo import IndexModel, ASCENDING, DESCENDING
    >>> index1 = IndexModel([("hello", DESCENDING),
    ... ("world", ASCENDING)], name="hello_world")
    >>> index2 = IndexModel([("goodbye", DESCENDING)])
    >>> db.test.create_indexes([index1, index2])
    ["hello_world"]
  • drop_index
    index_or_name: 索引编号或者索引的name

    my_collection.drop_index("mike")
  • drop_indexs
    删除所有索引

  • reindex
    重构索引,尽量少用,如果集合比较大多话,会很耗时耗力.

    for index in db.test.list_indexes():
    ... print(index)
    ...
    SON([(u'v', 1), (u'key', SON([(u'_id', 1)])),
    (u'name', u'_id_'), (u'ns', u'test.test')])
 
作者:Lomper 出处:http://www.cnblogs.com/lomper 关于作者:小菜鸟一枚,欢迎大神指点! 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接.

[转]pymongo常用操作函数的更多相关文章

  1. pymongo 常用操作函数

    pymongo 是 mongodb 的 python Driver Editor. 记录下学习过程中感觉以后会常用多一些部分,以做参考. 1. 连接数据库 要使用pymongo最先应该做的事就是先连上 ...

  2. byte数据的常用操作函数[转发]

    /// <summary> /// 本类提供了对byte数据的常用操作函数 /// </summary> public class ByteUtil { ','A','B',' ...

  3. Python--set常用操作函数

    python提供了常用的数据结构,其中之一就是set,python中的set是不支持索引的.值不能重复.无需插入的容器. 简单记录下set常用的操作函数: 1.新建一个set: set("H ...

  4. JavaScript之数组的常用操作函数

    js对数组的操作非常频繁,但是每次用到的时候都会被搞混,都需要去查相关API,感觉这样很浪费时间.为了加深印象,所以整理一下对数组的相关操作. 常用的函数 concat() 连接两个或更多的数组,并返 ...

  5. MYSQL常用操作函数的封装

    1.mysql常用函数封装文件:mysql.func.php <?php /** * 连接MYSQL函数 * @param string $host * @param string $usern ...

  6. R语言︱基本函数、统计量、常用操作函数

    先言:R语言常用界面操作 帮助:help(nnet) = ?nnet =??nnet 清除命令框中所有显示内容:Ctrl+L 清除R空间中内存变量:rm(list=ls()).gc() 获取或者设置当 ...

  7. JavaScript之字符串的常用操作函数

    字符串的操作在js中非常繁琐,但也非常重要.在使用过程中,也会经常忘记,今天就对这个进行一下整理. String 对象 String 对象用于处理文本(字符串). new String(s); // ...

  8. javascript 数组的常用操作函数

    join() Array.join(/* optional */ separator) 将数组转换为字符串,可带一个参数 separator (分隔符,默认为“,”). 与之相反的一个方法是:Stri ...

  9. JavaScript字符串常用操作函数之学习笔记

    字符串简介 使用英文单引号或双引号括起来,如:’Hello’,”World”,但是不能首尾的单引号和双引号必须一致,交错使用,如果要打印单引号或者双引号,可以使用转义字符\’(单引号),\”(双引号) ...

随机推荐

  1. 笔记:Spring Cloud Feign Ribbon 配置

    由于 Spring Cloud Feign 的客户端负载均衡是通过 Spring Cloud Ribbon 实现的,所以我们可以直接通过配置 Ribbon 的客户端的方式来自定义各个服务客户端调用的参 ...

  2. 【漏洞】PHPCMS_V9.6.0 前台注册GETSHELL

    首先准备一台公网服务器,在上面新建一个一句话的txt文件.如下: 接着打开目标网站,点击注册,填写信息后点击提交,拦截该数据包. 将其中post提交的数据替换成我们的poc,poc如下: siteid ...

  3. 巧用linux版powershell,管理linux下的docker

    大家好,我把用powershell的docker马甲命令的好处,放在了页面下方,从第五章开始. powershell 传教士 原创文章 始于 2017-09-07 允许转载,但必须保留名字和出处,否则 ...

  4. Jenkins + Docker 持续集成

    Jenkins介绍 Jenkins是一个开源软件项目,是基于Java开发的一种持续集成工具,用于监控持续重复的工作,旨在提供一个开放易用的软件平台,使软件的持续集成变成可能. 安装部署Jenkins ...

  5. ubuntu apt-get安装、卸载软件命令及如何查看日志

    linux亮红灯的我,开始学习linux,学习使我快乐,大家一起来学习... 1.安装软件命令 sudo apt-get apache2     安装apache,安装在默认路径下,指定路径安装,其实 ...

  6. 手写ButterKnife

    开发中使用注解框架可以极大地提高编码效率,注解框架用到的技术可以分为两种,运行时注解跟编译时注解.运行时注解一般配合反射机制使用,编译时注解则是用来生成模板代码.这里我们分别使用这两种方法实现Butt ...

  7. linux小白成长之路10————SpringBoot项目部署进阶

    [内容指引] war包部署: jar包部署: 基于Docker云部署. 一.war包部署 通过"云开发"平台初始化的SpringBoot项目默认采用jar形式打包,这也是我们推荐的 ...

  8. 【Spring系列】Spring mvc整合redis(非集群)

    一.在pom.xml中增加redis需要的jar包 <!--spring redis相关jar包--> <dependency> <groupId>redis.cl ...

  9. 作业01-Java基本概念

    1.本周学习总结 本周学习了JVM,JDK,JRE三者之间的区别及联系,知道JDK包括JRE,JRE包括JVM,知道java语言与C语言的不同之处在于java语言可以依赖于虚拟机实现"编译一 ...

  10. LOW版统计词频

    import string path = 'waldnn' with open(path,'r') as text: words = [raw_word.strip(string.punctuatio ...