insert_one():
对一张不存在表插入数据,他会在插入数据同时自动生成数据表,
例如我要对chat表插入数据,插入一个空数据
import pymongo mongo_client = pymongo.MongoClient( host=‘192.168.0.112‘, port=27017, username="admin", password="123456" ) mongo_db = mongo_client["db1"] # 插入数据 res = mongo_db.chat.insert_one({}) print(res,res.inserted_id)
返回对象
<pymongo.results.InsertOneResult object at 0x0000000002EDBF08>
inserted_id 获取插入的数据的_id ObjectId
5cb0ba3abd99392b1427c25e
> db.chat.find() { "_id" : ObjectId("5cb0ba3abd99392b1427c25e") }
insert_many() :插入多条数据
import pymongo mongo_client = pymongo.MongoClient( host=‘192.168.0.112‘, port=27017, username="admin", password="123456" ) mongo_db = mongo_client["db1"] # 插入数据 res = mongo_db.chat.insert_many( [ { ‘name‘:"jack","age":13, }, { ‘name‘:"mike","age":33, }, ] ) print(res,res.inserted_ids)
拿到对象
<pymongo.results.InsertManyResult object at 0x0000000002EDAF88>
inserted_ids 可以返回多个插入的数据的 _id objectID
[ObjectId(‘5cb0bbf9bd993914d8b5d82c‘), ObjectId(‘5cb0bbf9bd993914d8b5d82d‘)]
原文地址:https://www.cnblogs.com/mingerlcm/p/10699489.html
时间: 2024-10-24 19:50:57