Python连接操作MongoDB

用Python去操作MongoDB大致和命令行手敲语句差不多,基本增删改查如下,NoSql数据库中数据修改操作较复杂,建议直接干掉,然后重新插入,Mongo中还自带了一些聚合函数,排序语法,where语法等。

import pymongo
# 连接mongodb数据库填入ip和端口号
mongo_client = pymongo.MongoClient("mongodb://ip:port/")
# 指定数据库名称
db = mongo_client["mldn"]
# 指定集合名称
collection_demo = db['emp']
# 打印所有的集合名称
print(db.collection_names())
# 查询一条数据
one_data = collection_demo.find_one()
print(one_data)
# 多条数据+筛选
many_data = collection_demo.find({"loc": "北京"})
print(list(many_data))
# 添加数据
data_list = [
    {"name": "李四", "sex": "男", "age": 19, "score": 89},
    {"name": "赵五", "sex": "男", "age": 19, "score": 89},
    {"name": "钱六", "sex": "男", "age": 16, "score": 89},
    {"name": "张七", "sex": "男", "age": 17, "score": 89},
    {"name": "张八", "sex": "男", "age": 18, "score": 89},
    {"name": "张一", "sex": "男", "age": 19, "score": 89},
    {"name": "张二", "sex": "男", "age": 20, "score": 89},
    {"name": "张十", "sex": "男", "age": 21, "score": 89},
    {"name": "张九", "sex": "男", "age": 19, "score": 89},
]
# 一条一条插入
for each_data in data_list:
    collection_demo.insert_one(each_data)
# 整体插入
collection_demo.insert_many(data_list)
# 删除数据
delete_demo = collection_demo.delete_many({"name": "张一"})
print(delete_demo)

你可能感兴趣的:(MongoDB,Python)