轻松上手,快乐学习!

Python MongoDB 插入数据


一个文档在MongoDB中就像是SQL数据库中的一个记录。

插入集合

我们使用 insert_one()方法,将记录或文档插入到MongoDB的集合。 insert_one()方法的第一个参数是一个字典,其中包含插入的文档中包含字段名称和值。

实例

在“customers”集合中插入记录:
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mydict = { "name": "John", "address": "Highway 37" }

x = mycol.insert_one(mydict)
运行实例 »

返回 _id 字段

insert_one()方法返回一个 InsertOneResult 对象,该对象有一个属性inserted_id,该对象包含插入文档的id

实例

在“customers”集合中插入另一条记录,并返回该_id字段的值 :
mydict = { "name": "Peter", "address": "Lowstreet 27" }

x = mycol.insert_one(mydict)

print(x.inserted_id)
运行实例 »
如果您没有指定_id字段,那么MongoDB将为您添加一个字段并为每个文档分配唯一的ID。 在上面的示例中,_id未指定任何字段,因此MongoDB为记录(文档)分配了唯一的_id

插入多个文档

要将多个文档插入MongoDB中的集合,我们使用 insert_many()方法。 insert_many()方法的第一个参数是一个包含字典的列表,其中包含您要插入的数据:

实例

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mylist = [
  { "name": "Amy", "address": "Apple st 652"},
  { "name": "Hannah", "address": "Mountain 21"},
  { "name": "Michael", "address": "Valley 345"},
  { "name": "Sandy", "address": "Ocean blvd 2"},
  { "name": "Betty", "address": "Green Grass 1"},
  { "name": "Richard", "address": "Sky st 331"},
  { "name": "Susan", "address": "One way 98"},
  { "name": "Vicky", "address": "Yellow Garden 2"},
  { "name": "Ben", "address": "Park Lane 38"},
  { "name": "William", "address": "Central st 954"},
  { "name": "Chuck", "address": "Main Road 989"},
  { "name": "Viola", "address": "Sideway 1633"}
]

x = mycol.insert_many(mylist)

#print list of the _id values of the inserted documents:
print(x.inserted_ids)
运行实例 »
insert_many()方法返回一个InsertManyResult对象,该对象具有一个属性inserted_ids,用于保存插入文档的ID。

插入多个文档时指定ID

如果您不希望MongoDB为您的文档分配唯一ID,则可以在插入文档时指定_id字段。 请记住,值必须是唯一的。两个文件不能具有相同的_id

实例

PYTHON标题
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mylist = [
  { "_id": 1, "name": "John", "address": "Highway 37"},
  { "_id": 2, "name": "Peter", "address": "Lowstreet 27"},
  { "_id": 3, "name": "Amy", "address": "Apple st 652"},
  { "_id": 4, "name": "Hannah", "address": "Mountain 21"},
  { "_id": 5, "name": "Michael", "address": "Valley 345"},
  { "_id": 6, "name": "Sandy", "address": "Ocean blvd 2"},
  { "_id": 7, "name": "Betty", "address": "Green Grass 1"},
  { "_id": 8, "name": "Richard", "address": "Sky st 331"},
  { "_id": 9, "name": "Susan", "address": "One way 98"},
  { "_id": 10, "name": "Vicky", "address": "Yellow Garden 2"},
  { "_id": 11, "name": "Ben", "address": "Park Lane 38"},
  { "_id": 12, "name": "William", "address": "Central st 954"},
  { "_id": 13, "name": "Chuck", "address": "Main Road 989"},
  { "_id": 14, "name": "Viola", "address": "Sideway 1633"}
]

x = mycol.insert_many(mylist)

#print list of the _id values of the inserted documents:
print(x.inserted_ids)
运行实例 »