Python MongoDB如何使用insert_many查询?示例

2021年3月29日18:23:38 发表评论 1,639 次浏览

MongoDB是一个跨平台的面向文档的非关系(即NoSQL)数据库程序。它是一个开放源代码文档数据库, 以键值对的形式存储数据。 MongoDB由MongoDB Inc.开发, 最初于2009年2月11日发布。它使用C++, Go, JavaScript, Python语言编写。 MongoDB提供高速, 高可用性和高可伸缩性。

insert_many()

此方法用于在集合或MongoDB的数据库中插入多个条目。此方法的参数是一个列表, 其中包含我们要在集合中插入的数据的字典。

此方法返回类"〜pymongo.results.InsertManyResult"的实例, 该实例具有一个" _id"字段, 该字段保存插入文档的ID。如果文档未指定" _id"字段, 则MongoDB会将" _id"字段添加到列表中的所有数据, 并在插入之前为文档分配唯一的对象ID。

语法:collection.insert_many(documents, ordered = True, bypass_document_validation = False, session = None)
参数:
'documents':要迭代插入的文档。
"ordered"(可选):如果将按提供的顺序在服务器上依次插入"真"(默认)文档。如果发生错误, 则所有剩余的插入都将中止。如果为" False", 则将以任意顺序(可能并行)将文件插入服务器中, 并尝试所有文件插入。
" bypass_document_validation"(可选):如果为" True", 则允许写入选择退出文档级验证。默认值为" False"。
"session"(可选):类"〜pymongo.client_session.ClientSession"。

范例1:在此示例中, 提供了_id。

# importing Mongoclient from pymongo
from pymongo import MongoClient 
  
  
myclient = MongoClient( "mongodb://localhost:27017/" )
  
# database 
db = myclient[ "GFG" ]
  
# Created or Switched to collection 
# names: lsbin
collection = db[ "Student" ]
  
# Creating a list of records which we 
# insert in the collection using the
# update_many() method.
mylist = [
   { "_id" : 1 , "name" : "Vishwash" , "Roll No" : "1001" , "Branch" : "CSE" }, { "_id" : 2 , "name" : "Vishesh" , "Roll No" : "1002" , "Branch" : "IT" }, { "_id" : 3 , "name" : "Shivam" , "Roll No" : "1003" , "Branch" : "ME" }, { "_id" : 4 , "name" : "Yash" , "Roll No" : "1004" , "Branch" : "ECE" }, ]
  
# In the above list _id field is provided so it inserted in 
# the collection as specified.
  
# Inseting the entire list in the collection
collection.insert_many(mylist)

输出如下:

python-mongodb-insert-many

范例2:在此示例中, 未提供_id, 它是由MongoDB自动分配的。

# importing Mongoclient from pymongo
from pymongo import MongoClient 
  
  
myclient = MongoClient( "mongodb://localhost:27017/" )
  
# database 
db = myclient[ "GFG" ]
  
# Created or Switched to collection
# names: lsbin
collection = db[ "Geeks" ]
  
# Creating a list of records which we 
# insert in the collection using the
# update_many() method.
mylist = [
   { "Manufacturer" : "Honda" , "Model" : "City" , "Color" : "Black" }, { "Manufacturer" : "Tata" , "Model" : "Altroz" , "Color" : "Golden" }, { "Manufacturer" : "Honda" , "Model" : "Civic" , "Color" : "Red" }, { "Manufacturer" : "Hyundai" , "Model" : "i20" , "Color" : "white" }, { "Manufacturer" : "Maruti" , "Model" : "Swift" , "Color" : "Blue" }, ]
# In the above list we do not specify the _id, the MongoDB assigns 
# a unique id to all the records in the collection by default.
  
# Inseting the entire list in the collection
collection.insert_many(mylist)

输出:

python-mongodb-insert-many-2

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: