pymongo 安装与使用

Linux 下的Python包安装比较方便,使用pip命令即可安装
若系统还未安装pip,可使用
sudo apt install pip
进行安装,在16.04之后可使用 apt 替换 apt-get,少打四个字符也是极好的

安装

还是来看官方文档, Python MongoDB Drivers 有:

先看 Installation

使用 python -m pip install pymongo 即可安装最新版本,然后就安装完成了(就这些…)

快速入门

参见Tutorial

导入、连接与插入

# coding: utf-8

# 导入
from pymongo import MongoClient
# client 实例
client = MongoClient('localhost', 27017)
# 连接数据库
db = client.test_database
# 获取 collection
collection = db.test_collection

# 在Python中的字典(dict)可与JSON互转,因此插入时可直接使用dict
import datetime
post = {"author": "Mike",
...         "text": "My first blog post!",
...         "tags": ["mongodb", "python", "pymongo"],
...         "date": datetime.datetime.utcnow()}

# 使用 insert_one() 进行插入操作
posts = db.posts    # it's a collection
post_id = posts.insert_one(post).inserted_id
print post_id    # ObjectId('...')
# ''_id" 属性必须是唯一的
# 插入首个文档后,posts这个collection才真正被创建,可用以下命令查看
db.collection_names()    # [u'posts']

查找

# coding:utf-8

# find_one() 查找单个文档
# it is useful when you know there is only one matching document,
# or are only interested in the first match.
import pprint
pprint.pprint(posts.find_one())
'''
{u'_id': ObjectId('...'),
 u'author': u'Mike',
 u'date': datetime.datetime(...),
 u'tags': [u'mongodb', u'python', u'pymongo'],
 u'text': u'My first blog post!'}
'''

# find_one() 也可接受参数用于查找特定元素
posts.find_one({"author": "Eliot"})

# 注意ObjectId不是字符串类型,使用时需要转换
post_id_as_str = str(post_id)
posts.find_one({"_id": post_id_as_str})    # No result
# 应该这样
from bson.objectid import ObjectId
# The web framework gets post_id from the URL and passes it as a string
def get(post_id):
    # Convert from string to ObjectId:
    document = client.db.collection.find_one({'_id': ObjectId(post_id)})

关于unicode

PyMongo decodes each BSON string to a Python unicode string, not a regular str.
You can read more about Python unicode strings here.

使用 insert_many() 插入多个

# insert_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)
>>> result.inserted_ids
[ObjectId('...'), ObjectId('...')]

new_posts[1] has a different “shape” than the other posts – there is no “tags” field and we’ve added a new field, “title”. This is what we mean when we say that MongoDB is schema-free.

注意两个文档的不同之处,说明MongoDB是无模式数据库

使用find() 查找多个

用法与find_one()一致,只是返回的数量区别

使用count()计数

posts.count()
posts.find({"author": "Mike"}).count()

指定范围查找

有更多的高级查找方式advanced queries
举例如下:
posts.find({"date": {"$lt": now}})

索引

result = db.profiles.create_index([('user_id', pymongo.ASCENDING)], unique=True)
print sorted(list(db.profiles.index_information()))
# [u'_id_', u'user_id_1']

API 文档

API Documentation

    原文作者:Leoshi
    原文地址: https://www.jianshu.com/p/e67fa3c5b6d9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞