-
连接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)