【Python 模块】pymongo 基本使用

安装 & 加载

pip3 install pymongo -i https://mirrors.aliyun.com/pypi/simple/

import pymongo

连接 MongoDB 服务

client = pymongo.MongoClient("mongodb://localhost:27017/")
print(client)
-------------- 
# Mongo服务
MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True)

获取所有数据库

dblist = client.list_database_names()
print(dblist)
-------------
# 所有数据库名称
['admin', 'config', 'local']

创建数据库 & 获取数据库对象

如果没有该数据库 则创建

db = client["db"]
print(db)
---------
# db 数据库对象
Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'db')

创建集合 & 获取集合

如果没有该集合 则创建

# 创建集合
collection = db["collection"]
print(sets)
-----------
# sets 集合对象
Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'db'), 'sets')

# 获取所有集合
sets = db.list_collection_names()
print(sets)
--------------
# 该数据库所有集合
['collection']

插入数据

# 插入一条数据
data = {"name":"bigdataboy","age":"18"}
x = collection.insert_one(data)
print(x.inserted_id)
--------
# 数据的 _id
5ed666e1bca2037c30662e97

# 插入多条数据
datas = [
    {"name": "大数据男孩", "age": "18"},
    {"name": "bigdataboy", "age ":"16", "addr": "China"},
    {"name": "bigdataboy", "age ":"18"}
]
x = collection.insert_many(datas)
print(x.inserted_ids)
---------------------
# 插入数据的 _id
[ObjectId('5ed667e044fb69d445e510d8'), ObjectId('5ed667e044fb69d445e510d9'), ObjectId('5ed667e044fb69d445e510da')]

自定义 _id

# 链式写法
collection = pymongo.MongoClient("mongodb://localhost:27017/")["db"]["collection"]

# 数据自行固定 _id
datas = [
    {"_id":"1" ,"name":"大数据男孩", "age":"18"},
    {"_id":"2" ,"name": "bigdataboy", "age":"16", "addr":"China"},
    {"_id":"3" ,"name": "bigdataboy", "age":"18"}
]
i = collection.insert_many(datas)
print(i.inserted_ids)
---------------------
# 插入数据的 _id
['1', '2', '3']

查看所有数据

collection = pymongo.MongoClient("mongodb://localhost:27017/")["db"]["collection"]
for x in collection.find():
    print(x)
------------
# 所有数据
{'_id': '1', 'name': '大数据男孩', 'age': '18'}
{'_id': '2', 'name': 'bigdataboy', 'age': '16', 'addr': 'China'}
{'_id': '3', 'name': 'bigdataboy', 'age': '18'}
发表评论 / Comment

用心评论~