python 访问 mongodb

创建日期: 2022-09-01 14:06 | 作者: 风波 | 浏览次数: 21 | 分类: MongoDB

参考: - https://www.runoob.com/python3/python-mongodb.html

官方文档:https://pymongo.readthedocs.io/en/stable/tutorial.html


1. 安装 pymongo

pip install pymongo -i https://pypi.douban.com/simple/ --trusted-host pypi.douban.com

2. 使用 pymongo

# -*- coding: utf-8 -*-

import pymongo

myclient = pymongo.MongoClient("mongodb://username:password@localhost:27017/") # Making a Connection with MongoClient
mydb = myclient["dbname"] # 选择数据库  Getting a Database

# 获取所有的 DB
dblist = myclient.list_database_names()
for db in dblist:
    print(db)

# 插入数据
mycol = mydb["animal"] # Getting a Collection
mydict = { "name": "RUNOOB", "alexa": "10000", "url": "https://www.runoob.com" }
x = mycol.insert_one(mydict)

# 读取数据
x = mycol.find_one()
print(x)

3. 根据条件进行查询

3.1 Querying By ObjectId

doc = posts.find_one({"_id": post_id})

Note that an ObjectId is not the same as its string representation:

post_id_as_str = str(post_id)
posts.find_one({"_id": post_id_as_str})  # No result

A common task in web applications is to get an ObjectId from the request URL and find the matching document. It’s necessary in this case to convert the ObjectId from a string before passing it to find_one:

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)})

3.2 Getting a Single Document With find_one()

import pprint
pprint.pprint(posts.find_one())

find_one() also supports querying on specific elements that the resulting document must match. To limit our results to a document with author “Mike” we do:

pprint.pprint(posts.find_one({"author": "Mike"}))

3.3 Querying for More Than One Document

To get more than a single document as the result of a query we use the find() method. find() returns a Cursor instance, which allows us to iterate over all matching documents. For example, we can iterate over every document in the posts collection:

for post in posts.find():
    pprint.pprint(post)

Just like we did with find_one(), we can pass a document to find() to limit the returned results. Here, we get only those documents whose author is “Mike”:

for post in posts.find({"author": "Mike"}):
    pprint.pprint(post)

3.4 Counting

posts.count_documents({})
posts.count_documents({"author": "Mike"})

3.5 Range Queries

d = datetime.datetime(2009, 11, 12, 12)
for post in posts.find({"date": {"$lt": d}}).sort("author"):
    pprint.pprint(post)

3.6 Indexing

Adding indexes can help accelerate certain queries and can also add additional functionality to querying and storing documents. In this example, we’ll demonstrate how to create a unique index on a key that rejects documents whose value for that key already exists in the index.

First, we’ll need to create the index:

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

Notice that we have two indexes now: one is the index on _id that MongoDB creates automatically, and the other is the index on user_id we just created.

Now let’s set up some user profiles:

user_profiles = [{"user_id": 211, "name": "Luke"}, {"user_id": 212, "name": "Ziltoid"}]
result = db.profiles.insert_many(user_profiles)

The index prevents us from inserting a document whose user_id is already in the collection:

>>> 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):
DuplicateKeyError: E11000 duplicate key error index: test_database.profiles.$user_id_1 dup key: { : 212 }

4. Insert 数据

4.1 Inserting a Document

posts = db.posts
post_id = posts.insert_one(post).inserted_id

如果执行命令 db.list_collection_names() 那么会显示如下内容

['posts']

4.2 Bulk Inserts

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
21 浏览
22 爬虫
0 评论