Pymongo向mongodb插入数据, 可以分为单文档插入和多文档插入, 默认情况下, 插入数据时,mongodb会自动生成_id作为主键, _我们自己也可以给_id赋值, 不过,需要注意的是, _id作为主键必须是唯一的,重复出现则会报错。
单文档插入
单文档插入,使用insert_one()方法,第一个参数是插入的文档,也就是python中的字典。我们向数据库db_1中的集合students插入一条记录,在mongdb中, 如果我们使用到的数据库或集合不存在, mongodb会自动生成该数据库或集合, 因此, 即使数据库或集合不存在, 我们也不需要手动去生成。
from pymongo import MongoClient
host = "localhost"
port = 27017
client = MongoClient(host, port)
db_1 = client["db_1"]
students_collection = db_1["students"]
document_1 = {"name": "Tom", "age":18}
res = students_collection.insert_one(document_1)
inserted_id = res.inserted_id
print(inserted_id)
insert_one()函数返回一个InsertOneResult对象,该对象有一个属性inserted_id, 就是新插入文档的主键_id的值。
多文档插入
同时插入多个文档使用insert_many()方法, 参数是一个列表, 列表里面的元素是要插入的文档, 也就是python中的字典,每个文档的键是不需要保持一致的。我们向students集合中插入多个文档, 文档中有name, age,gender字段。
from pymongo import MongoClient
host = "localhost"
port = 27017
client = MongoClient(host, port)
db_1 = client["db_1"]
students_collection = db_1["students"]
documents = [{"name": "zhangsan", "age":17}, {"name":"lisi", "gender": "male"}, {"name": "wangwu", "age": 17, "gender": "male"}]
res = students_collection.insert_many(documents)
inserted_ids = res.inserted_ids
print(inserted_ids)
insert_many()函数返回一个InsertManyResult对象,该对象有一个inserted_ids属性,可以获取插入的文档的id的列表。