MongoDB与python交互

MongoDB与python交互

插入数据

# 插入单条数据
from pymongo import MongoClient
from urllib.parse import quote_plus

# 连接MongoDB数据库
# 第一种无密码连接数据库的方式
# client = MongoClient()  # 如果是本机连接host,post参数可以省略
# db = client['test']
# site = db['demo']

# 第二种有密码连接数据库的方式
user = 'shuai'
password = 'shuai'
host = '127.0.0.1'
port = 27017
url = 'mongodb://%s:%s@%s'%(quote_plus(user),
                            quote_plus(password),
                            host)

# quote_plus函数:对url进行编码
# 也可以直接拼接mongodb的url
# url = 'mongodb://shuai:shuai@127.0.0.1'
# url = 'mongodb://用户:密码@url'
client = MongoClient(url,port=port)
# collection = client['test']['demo']
collection = client.test.demo

my_dict = {'name':'小帅','age':21,'gender':'male'}

msg = collection.insert_one(my_dict)
"""
insert_one() 方法返回 InsertOneResult 对象,该对象包含 inserted_id 属性,它是插入文档的 id 值。
"""
print(msg)   #  返回 _id 字段
print(msg.inserted_id)  # 插入文档时没有指定 _id,MongoDB 会为每个文档添加一个唯一的 id。


# 插入多条数据
url = 'mongodb://shuai:shuai@127.0.0.1'

client = MongoClient(url)
col = client['test']['demo1']

# mylist = [
#   { "name": "Taobao", "age": "100", "url": "https://www.taobao.com" },
#   { "name": "QQ", "age": "101", "url": "https://www.qq.com" },
#   { "name": "Facebook", "age": "10", "url": "https://www.facebook.com" },
#   { "name": "知乎", "age": "103", "url": "https://www.zhihu.com" },
#   { "name": "Github", "age": "109", "url": "https://www.github.com" }
# ]

mylist = [
  { "_id": 1, "name": "RUNOOB", "cn_name": "菜鸟教程"},
  { "_id": 2, "name": "Google", "address": "Google 搜索"},
  { "_id": 3, "name": "Facebook", "address": "脸书"},
  { "_id": 4, "name": "Taobao", "address": "淘宝"},
  { "_id": 5, "name": "Zhihu", "address": "知乎"}
]

# msg = col.insert_many(mylist)
# print(msg.inserted_ids)

"""
插入数据的列表中有_id数据的在列表中打印出来,
如果没有指定_id字段,MongoDB 会为每个文档添加一个唯一的 id。
"""

查询数据

# 查询所有数据
for i in col.find():
    print(i)
   
# find()括号里指定查询条件
for i in col.find({},{'_id': 0,'name':1,'age':1 }):
    print(i)

"""
除了_id,你不能在一个对象中同时指定 0 和 1,如果你设置了一个字段为 0,则其他都为 1,反之亦然。
"""

for i in col.find({},{'_id': 0,'name':0,'age':1 }):
    print(i)   # 报错

更新数据

# 跟新一条数据
my_query = {'name':'QQ'}
new_values = {'$set':{'name':'小帅'}}

msg = col.update_one(my_query,new_values)
print(msg.modified_count,'文档已修改')   # 文档已修改加以说明 

# 更新多条数据
my_query = {'name':{'$regex':'^F'}}   # 正在匹配数据
new_values = {"$set":{'name':'少帅'}}

msg = col.update_many(my_query,new_values)
print(msg.modified_count)

排列数据

"""
sort() 方法可以指定升序或降序排序。
sort() 方法第一个参数为要排序的字段,第二个字段指定排序规则,1 为升序,-1 为降序,默认为升序。
"""
msg = col.find().sort("age") # 不写默认升序
for i in msg:
    print(i)

msg = col.find().sort("age",-1)  # 降序
for i in msg:
    print(i)

删除数据

# 删除一条数据
myquery = { "name": "小帅" }
msg = col.delete_one(myquery)
print(mag.deleted_count, "个文档已删除")

# 删除多条数据
msg = col.delete_many(myquery)

# 删除集合中的所有文档
msg = col.delete_many({})

# 删除集合
col.drop()
posted @ 2022-02-12 23:12  程序员少帅  阅读(51)  评论(0)    收藏  举报