当前位置 : 主页 > 编程语言 > python >

python操作mongodb

来源:互联网 收集:自由互联 发布时间:2021-06-25
安装python连接MongoDB的依赖 pip install pymongo 使用pymongo操作mongodb from pymongo import MongoClient# mongodb客户端连接对象 uri# client = MongoClient(‘localhost‘,27017)client = MongoClient(‘mongodb://localhost:2701

安装python连接MongoDB的依赖

pip install pymongo

使用pymongo操作mongodb

from pymongo import MongoClient

# mongodb客户端连接对象 uri
# client = MongoClient(‘localhost‘,27017)
client = MongoClient(‘mongodb://localhost:27017‘)

# 查看mongodb中的数据库
dbs = client.list_database_names()
print(dbs)

# 切换到名为taobao的数据库,没有会创建
db = client.taobao

插入数据

# 向products集合插入一条数据
db.products.insert_one({
    "img":"//g.alicdn.com/s.gif",
    "price":"¥39.60",
    "title":"黑麦全麦面包代餐饱腹无糖精低粗粮脂早餐整箱吐司零食品速食懒人",
    "deal":"deal",
    "shop":"友臣旗舰店",
    "location":"福建 泉州"
})

# 插入多条数据
db[‘products‘].insert_many([
    {
        "img":"//g.alicdn.com/s.gif",
        "price":"¥19.60",
        "title":"黑麦全麦面包代餐饱腹无糖精低粗粮脂早餐整箱吐司零食品速食懒人",
        "deal":"deal",
        "shop":"好欢螺旗舰店",
        "location":"福建 泉州"
    },
    {
        "img":"//g.alicdn.com/s.gif",
        "price":"¥49.60",
        "title":"科尔沁手撕风干牛肉干400g原味内蒙古特产牛肉干美食零食小吃",
        "deal":"deal",
        "shop":"天猫超市",
        "location":"上海"
    }
]) 

查询数据

# 查询一条数据
result = db.products.find_one()
print(result)
print(type(result))
print(result["img"])

# 查询products集合有多少文档
results = db.products.find()
print(results)
print(type(results))
# 遍历结果集
for item in results:
    print(item)

# 查询location为上海的数据
items = db.products.find({‘location‘:‘上海‘})
for item in items:
    print(item)

# 查询指定字段的数据,将要返回的字段对应值设置为 1
items = db.products.find({},{"_id": 0, "location": 1, "price": 1 })
for item in items:
    print(item)

 and查询

items = db.products.find({"shop":"好欢螺旗舰店","location":"上海"})
for item in items:
    print(item)

or查询

items = db.products.find({"$or":[{"shop":"好欢螺旗舰店"},{"location":"上海"}]})
for item in items:
    print(item)

 范围查询

from pymongo import MongoClient

# mongodb客户端连接对象 uri
# client = MongoClient(‘localhost‘,27017)
client = MongoClient(‘mongodb://localhost:27017‘)


# 切换到名为taobao的数据库,没有会创建
db = client.school

coll = db[‘students‘]

coll.insert_one({
    ‘name‘:‘Tom‘,
    ‘age‘:20,
    ‘height‘:177,
    ‘class‘:‘实验一班‘
})

coll.insert_many([
    {
        ‘name‘:‘Alex‘,
        ‘age‘:32,
        ‘height‘:175,
        ‘class‘:‘实验一班‘
    },
    {
        ‘name‘:‘Jack‘,
        ‘age‘:16,
        ‘height‘:181,
        ‘class‘:‘实验二班‘
    },
    {
        ‘name‘:‘老王‘,
        ‘age‘:35,
        ‘height‘:169,
        ‘class‘:‘实验二班‘
    }
])


condition = {‘gt‘:‘大于‘,‘lt‘:‘小于‘,‘eq‘:‘等于‘,‘gte‘:‘大于等于‘,‘lte‘:‘小于等于‘,‘ne‘:‘不等于‘}

# 查询年龄大于20的学生
items = coll.find({‘age‘:{‘$gt‘:20}})
for item in items:
    print(item)

更新

网友评论