Python 连接 mongoDB、查询集合数据

1 mongodb 数据库的安装

2 python 连接 mongodb 的驱动程序,pip install pymongo

#!/usr/bin/python3

#TODO:

import os
import pymongo
import json

myclient = pymongo.MongoClient('mongodb://localhost:27017/')  #连接mangodb数据库
dblist = myclient.list_database_names()  #读取 MongoDB 中的所有数据库

#插入字典 单个数据
def insert_data(dict_rule):
    myrule.insert_one(dict_rule)  # 集合中插入文档使用 insert_one() 方法,该方法的第一参数是字典 name => value 对
    return

#插入字典 多个数据
def insert_many(dict_list):  # 该方法的第一参数是字典列表
    myrule.insert_many(dict_list)
    return

#查询字典
def select_data(field_name,value):
    result = myrule.find_one({field_name:value})
    print(result)
    return result

#修改字典
def change_data(field_name,old_value,new_value):
    myquery = {field_name: old_value}
    new_value = {myrule: {field_name:new_value}}
    myrule.update_one(myquery, new_value) # update_one() 方法修改文档中的记录。该方法第一个参数为查询的条件,第二个参数为要修改的字段
    return

# 排序字典
def sort_data(field_name):
    for x in myrule.find().sort(field_name,-1):  #1 为升序,-1 为降序,默认为升序。
        print(x)

def delete_data(field_name,value):
    myquery = {field_name,value}
    myrule.delete_one(myquery)  #delete_one() 方法来删除一个文档,该方法第一个参数为查询对象,指定要删除哪些数据。

#加载json文件
def load_json(file_name):
    with open(file_name,'r') as f:
        text = json.loads(f)
        print(f)
        for line in text:
            print(line)

if __name__ == '__main__':
    # 连接数据库
    mydb = myclient["sets"]  # 打开名称为 sets 的数据库
    myrule = mydb['popblock']  # 打开 sets 数据库下的名称为 popblock 的集合

    # 数据库不存在
    if "sets" not in dblist:
        mydict = {"rule_id": "1"}
        insert_data(mydict)  # MongoDB 中,集合只有在内容插入后才会创建! 创建集合(数据表)后要再插入一个文档(记录),集合才会真正创建。
        print("数据库创建成功!")
    # 数据库存在
    else:
        file_name = r'D:\xxxxxx\xxxxxxxxx.json'
        with open(file_name, 'r', encoding='UTF-8') as f:
            json_data = json.loads(f.read())
            for line in json_data['rules']:
                insert_data(line)
        print("数据库更新完成!")

    #查询
    select_data('xxxxxxx','xxxxx')

 

3 pycharm 安装 mongo explorer 插件

4.数据库的连接、创建、增、删、改、查等:

 

 

#coding=utf-8

#C:\MongoDB

import pymongo
import csv
import xlrd

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

#1、创建数据库=给Excel命名
mydb = myclient["softcenter"]

#2、在文件下创建表单=在Excel中添加sheet
sheet_tabs_soft = mydb['softinfo']

#3、将excel中的软件数据存入到数据库中
file_path = r'C:\Users\Desktop\soft.xlsx'

xlsx = xlrd.open_workbook(file_path)  #打开文件
sheet1 = xlsx.sheets()[0]    # 获得第1张sheet,索引从0开始
row =sheet1.nrows
for line in range(row):
    rowdate = sheet1.row_values(line)  # i行的list
    data = {
        'name': rowdate[1],
        'appid': rowdate[2]
    }
    sheet_tabs_soft.insert_one(data)

#5、将数据库中存放的数据打印输出,find函数中特殊字符的使用方法
for item in sheet_tabs_soft.find({'name':'爱奇艺'}):
    print(item)

 

可以调用count()方法来统计查询结果的条数。

count = collection.find({'gender': "male"}).count()
print(count)

 

 

 

 

 

 

 

 

 

 

posted @ 2022-01-21 18:17  chenwandong  阅读(1396)  评论(0编辑  收藏  举报