码迷,mamicode.com
首页 > 数据库 > 详细

python操作mongodb

时间:2019-10-10 00:21:20      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:base   数据库   any   com   集合   cli   lis   student   insert   

安装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)

更新

 

  

 

  

 

python操作mongodb

标签:base   数据库   any   com   集合   cli   lis   student   insert   

原文地址:https://www.cnblogs.com/snow-wolf-1/p/11644889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!