目录

Python MongoDB 插入


文档在 MongoDB 中与记录在 SQL 数据库中。

插入集合

要插入一条记录,或文档正如 MongoDB 中所说的那样,在集合中,我们使用insert_one()方法。

第一个参数insert_one()method 是一个字典,包含要插入的文档中每个字段的名称和值。

示例

在 "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。

示例

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)
运行示例 »