Mongo 数据库(python)

  • 连接MongoDB:(两种连接方式)

import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
client = pymongo.MongoClient('mongodb://localhost:27017/')
  • 指定数据库:(两种方式,连接 ‘test’ 数据库)

db = client['test']
db = client.test
  • 指定集合:(两种方式,指定 ‘student’ 集合)

数据库语法:db.getCollection('student')
collection = db['student']
collection = db.student
  • 插入数据:

## 数据库语法:
db.getCollection('表名').insert_one(student)
db.getCollection('表名').insert_many([student1, student2])
## Python3官方推荐使用:
# 单条数据插入:
collection.insert_one(student)
# 多条数据插入:
collection.insert_many([student1, student2])

## 不推荐使用
# 单条数据插入:
collection.insert(student)
# 多条数据插入:
collection.insert([student1, student2])

tip:'student' 为字典格式,返回值为 _id 值,多条则为 _id 的集合

  • 查找数据

## 数据库语法:
# 查询条件:filter
# 单个查询条件
filter = {'键': '值'}
# 多个查询条件
filter = {'键': '值', '键': '值'}
db.getCollection('表名').find(filter)
# 查询符合其中一个条件的
db.getCollection('product_rawMaterial').find({'$or': [{'product': '3D打印机'}, {'product':'金属材料'}]})

Python3
# 查询符合条件的一个(第一个)
collection.find_one(filter)
# 查询符合条件的全部
collection.find(filter)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值