Python MongoDB – insert_one查询用法介绍

2021年3月11日18:02:26 发表评论 1,066 次浏览

本文概述

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

insert_one()

通过这种方法, 我们可以在MongoDB的集合或数据库中插入单个条目。如果该集合不存在, 则此方法将创建一个新的集合并将数据插入其中。它以字典作为参数, 包含要在集合中插入的文档中每个字段的名称和值。

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

语法:collection.insert_one(document, bypass_document_validation = False, session = None)参数:'document':要插入的文档。必须是可变的映射类型。如果文档没有_id字段, 则会自动添加一个。 " bypass_document_validation"(可选):如果为" True", 则允许写入选择退出文档级验证。默认值为" False"。 "会话"(可选):类"〜pymongo.client_session.ClientSession"。

范例1: 

样本数据库:

Python MongoDB – insert_one查询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: lsbin
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)

输出如下:

Python MongoDB – insert_one查询2

范例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: lsbin
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)

输出如下: 

Python MongoDB – insert_one查询3

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

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


木子山

发表评论

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