Python MongoDB – insert_one 查询
MongoDB是一个跨平台的面向文档和非关系(即 NoSQL)的数据库程序。它是一个开源文档数据库,以键值对的形式存储数据。 MongoDB 由 MongoDB Inc. 开发,最初于 2009 年 2 月 11 日发布。它是用 C++、Go、JavaScript、 Python语言编写的。 MongoDB 提供高速、高可用性和高可扩展性。
插入一个()
这是一种我们可以在 MongoDB 中的集合或数据库中插入单个条目的方法。如果集合不存在,此方法将创建一个新集合并将数据插入其中。它将字典作为参数,其中包含要插入到集合中的文档中每个字段的名称和值。
此方法返回类“~pymongo.results.InsertOneResult”的一个实例,该实例具有一个“_id”字段,该字段保存插入文档的 id。如果文档未指定“_id”字段,则 MongoDB 将添加“_id”字段并在插入之前为文档分配唯一的对象 id。
Syntax: collection.insert_one(document, bypass_document_validation=False, session=None)
Parameters:
- ‘document’: The document to insert. Must be a mutable mapping type. If the document does not have an _id field one will be added automatically.
- ‘bypass_document_validation’ (optional): If “True”, allows the write to opt-out of document level validation. Default is “False”.
- ‘session’ (optional): a class ‘~pymongo.client_session.ClientSession’.
示例 1:
样本数据库:
Python3
# importing Mongoclient from pymongo
from pymongo import MongoClient
# Making Connection
myclient = MongoClient("mongodb://localhost:27017/")
# database
db = myclient["GFG"]
# Created or Switched to collection
# names: GeeksForGeeks
collection = db["Student"]
# Creating Dictionary of records to be
# inserted
record = { "_id": 5,
"name": "Raju",
"Roll No": "1005",
"Branch": "CSE"}
# Inserting the record1 in the collection
# by using collection.insert_one()
rec_id1 = collection.insert_one(record)
Python3
# importing Mongoclient from pymongo
from pymongo import MongoClient
# Making Connection
myclient = MongoClient("mongodb://localhost:27017/")
# database
db = myclient["GFG"]
# Created or Switched to collection
# names: GeeksForGeeks
collection = db["Student"]
# Creating Dictionary of records to be
# inserted
records = {
"record1": { "_id": 6,
"name": "Anshul",
"Roll No": "1006",
"Branch": "CSE"},
"record2": { "_id": 7,
"name": "Abhinav",
"Roll No": "1007",
"Branch": "ME"}
}
# Inserting the records in the collection
# by using collection.insert_one()
for record in records.values():
collection.insert_one(record)
输出:
示例 2:插入多个值
Python3
# importing Mongoclient from pymongo
from pymongo import MongoClient
# Making Connection
myclient = MongoClient("mongodb://localhost:27017/")
# database
db = myclient["GFG"]
# Created or Switched to collection
# names: GeeksForGeeks
collection = db["Student"]
# Creating Dictionary of records to be
# inserted
records = {
"record1": { "_id": 6,
"name": "Anshul",
"Roll No": "1006",
"Branch": "CSE"},
"record2": { "_id": 7,
"name": "Abhinav",
"Roll No": "1007",
"Branch": "ME"}
}
# Inserting the records in the collection
# by using collection.insert_one()
for record in records.values():
collection.insert_one(record)
输出: