欢迎来到JIA的博客

PyMongo基本用法

 

一、模块安装

安装:

pip install pymongo

二、数据库连接

2.1 数据库连接,无密码

import pymongo
mongo = pymongo.MongoClient("mongodb://127.0.0.1:27017/")

2.2 数据库连接,有密码

方式1:

import pymongo
from urllib import parse
username = parse.quote_plus('mofang')   # 对用户名进行编码
password = parse.quote_plus('123456')  # 对密码进行编码
database = "mofang" # 数据库名称
host     = "127.0.0.1"
port     = "27017"
mongo = pymongo.MongoClient('mongodb://%s:%s@%s:%s/%s' % ( username, password, host, port, database))

方式2:

import pymongo
from urllib import parse
username = parse.quote_plus('mofang')   # 对用户名进行编码
password = parse.quote_plus('123456')  # 对密码进行编码
database = "mofang" # 数据库名称
mongo = pymongo.MongoClient('mongodb://127.0.0.1:27017') # 组装成url进行连接
my_db = mongo["mofang"]
my_db.authenticate(username,password)

方式3:

import pymongo
from urllib import parse
username = parse.quote_plus('root')   # 对用户名进行编码
password = parse.quote_plus('123456')  # 对密码进行编码
host     = "127.0.0.1"
port     = "27017"
database = "mofang" # 数据库名称
mongo = pymongo.MongoClient('mongodb://%s:%s@%s:%s/admin' % ( username, password, host, port))
my_db = mongo[database]
my_collection = my_db["my_collection"] # 没有往集合里面保存文档之前,mongdb不会真正创建集合!

 

三、数据库管理

import pymongo

# 数据库连接
mongo = pymongo.MongoClient("mongodb://127.0.0.1:27017/")

# 创建数据库
my_db  = mongo["my_db"] # 没有往集合里面保存文档之前,mongdb不会真正创建集合!

# 查看数据库列表
print(mongo.list_database_names()) # 上面的 my_db 因为没有内容,所以没有被创建的。

四、集合管理

import pymongo

mongo = pymongo.MongoClient("mongodb://127.0.0.1:27017/")
my_db = mongo["my_db"]

my_collection = my_db["my_collection"] # 没有往集合里面保存文档之前,mongdb不会真正创建集合!

# 查看集合列表
print(my_db.list_collection_names())

# 删除集合
my_collection.drop() # 删除成功返回true,如果集合不存在,返回false

五、文档管理

5.1 添加文档

import pymongo
mongo = pymongo.MongoClient("mongodb://127.0.0.1:27017/")
my_db = mongo["my_db"]
my_collection = my_db["my_collection"]

# 添加一个文档
document = { "name": "xiaoming", "mobile": "13012345678","age":16}
ret = my_collection.insert_one(document)
print(ret.inserted_id) # 返回InsertOneResult对象
# 插入文档时,如果没有指定_id,将自动分配一个唯一的id。

# 添加多个文档
document_list = [
  { "name": "xiaoming", "mobile": "13033345678","age":17},
  { "name": "xiaohong", "mobile": "13044345678","age":18},
  { "name": "xiaohei",  "mobile": "13612345678","age":18},
]
ret = my_collection.insert_many(document_list)

# 打印文档_id值列表:
print(ret.inserted_ids)

 

5.2 删除文档

import pymongo

mongo = pymongo.MongoClient("mongodb://127.0.0.1:27017/")
my_db = mongo["my_db"]
my_collection = my_db["my_collection"]

# 删除一个文档
query = {"name":"xiaoming"}
my_collection.delete_one(query)

# 删除多个文档
query = { "mobile": {"$regex": "^130"} }
ret = my_collection.delete_many(query)
print("删除了%d个文档" % ret.deleted_count)

 

import pymongo
from urllib.parse import quote_plus

from bson import ObjectId

if __name__ == "__main__":
    username = quote_plus("mofang")
    password = quote_plus("123456")
    # 获取数据库连接对象
    mongo = pymongo.MongoClient(f"mongodb://{username}:{password}@127.0.0.1:27017/mofang")
    mofang = mongo["mofang"]
    user_list = mofang["user_list"]

    """删除文档"""
    query = {"_id": ObjectId("60d925e127bd4b7769251002")}
    ret = user_list.delete_one(query)
    print(ret)
    print(ret.deleted_count)
    """删除多个文档"""
    query = {"name": "xiaolan"}
    ret = user_list.delete_many(query)
    print(ret.deleted_count)

 

5.3 更新文档

import pymongo

mongo = pymongo.MongoClient("mongodb://127.0.0.1:27017/")
my_db = mongo["my_db"]
my_collection = my_db["my_collection"]

# 更新一个文档
query = { "name": "xiaoming" }
data = { "$set": { "age": 18 } }
my_collection.update_one(query, data)

# 更新所有文档
query = { "mobile": {"$regex": "^130"} }
data = { "$set": { "age": 18 } }
my_collection.update_many(query, data)

 

5.4 查询文档

import pymongo

mongo = pymongo.MongoClient("mongodb://127.0.0.1:27017/")
my_db = mongo["my_db"]
my_collection = my_db["my_collection"]

# 查看一个文档
ret = my_collection.find_one()
print(ret)

# 查看所有文档
for document in my_collection.find():
    print(document)

# 查看文档部分字段,find和find_one的第二个参数表示控制字段的显示隐藏,1为显示,0为隐藏
for document in my_collection.find({},{ "_id": 0, "name": 1, "mobile": 1 }):
    print(document)

# 条件查询
query = { "age": 18 }
document_list = my_collection.find(query)
for document in document_list:
    print(document)

# 比较运算符
query = { "age": {"$gt":17} }
document_list = my_collection.find(query)
for document in document_list:
    print(document)

# 排序显示
# 单个字段排序:
#         sort("键", 1) 升序
#         sort("键",-1) 降序

# 多个字段排序:
#       sort([("键1",1),("键2",-1)])
document_list = my_collection.find().sort("age")
for document in document_list:
    print(document)
    
# 限制查询结果数量
document_list = my_collection.find().limit(3)
print(document_list)

# 偏移、跳过
#    skip(int)
document_list = my_collection.find().limit(3).skip(3) # 从第3篇文档开始获取3篇文档
print(document_list)

# 自定义条件函数
document_list = my_collection.find({"$where":"this.age==18"})
print(document_list)

 

posted @ 2021-06-28 10:51  讷言敏行~  阅读(4031)  评论(0编辑  收藏  举报