Python RPA 数据库篇 3 - MongoDB 篇 2 - 连接 MongoDB 数据库

Python RPA 数据库篇 3 - MongoDB 篇 2 - 连接 MongoDB 数据库

代码

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
# @Software: PyCharm
# @virtualenv:workon
# @contact: contact information
# @Desc:Code descripton
__author__ = '未昔/AngelFate'
__date__ = '2019/8/27 20:59'

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["runoobdb"] # 创建数据库

dblist = myclient.list_database_names()

if "runoobdb" in dblist:
 print("runoobdb 数据库已存在!")
else:
 print("runoobdb 数据库已存在!")

mycol = mydb["sites"]
mycol.insert({"name": "wangwei", "age": 3})

collist = mydb.list_collection_names()
# collist = mydb.collection_names()
# PS: 注意:collection_names 在最新版本的 Python 中已废弃,Python3.7+ 之后的版本改为了 list_collection_names()。
if "sites" in collist: # 判断 sites 集合是否存在
 print("集合已存在!")

for i in collist:
 print(i)

for i in mycol.find():
 print(i)

结果

PS:insert 方法将在 py7.5 以上高版本弃用

D:\import\python3.7\python.exe E:/python/Study/数据库篇/MongoDB数据库/class1.py
runoobdb 数据库已存在!
E:/python/Study/数据库篇/MongoDB数据库/class1.py:24: DeprecationWarning: insert is deprecated. Use insert_one or insert_many instead.
集合已存在!
sites.sites
sites
mycol.insert({"name": "wangwei", "age": 3})
{'_id': ObjectId('5d65e2bb5b28a2d4bc75da44'), 'name': 'wangwei', 'age': 18}
{'_id': ObjectId('5d65e3a9f250dcab8e226876'), 'name': 'wangwei', 'age': 18}
{'_id': ObjectId('5d65e87149bde3db19bc5ac4'), 'name': 'wangwei', 'age': 19}
{'_id': ObjectId('5d65e8932034d2c79f82e91d'), 'name': 'wangwei', 'age': 19}
{'_id': ObjectId('5d65e8a5f12eb3cd7d34706a'), 'name': 'wangwei', 'age': 19}
{'_id': ObjectId('5d65e8c033e158f2b34ee6af'), 'name': 'wangwei', 'age': 19}
{'_id': ObjectId('5d65e8d2c4daef8833f34e2b'), 'name': 'wangwei', 'age': 19}
{'_id': ObjectId('5d65e8e5d79cae433374dec3'), 'name': 'wangwei', 'age': 19}
{'_id': ObjectId('5d65ea00e6466f5a2354982e'), 'name': 'yangling', 'age': 19}
{'_id': ObjectId('5d65ebdc3c01f2df59bae676'), 'name': 'wangwei', 'age': 3}

Process finished with exit code 0