Python MongoDB 插入文檔
- 上一頁 MongoDB 創建集合
- 下一頁 MongoDB Find
MongoDB 中的文檔與 SQL 數據庫中的記錄相同。
插入集合
要在 MongoDB 中把記錄或我們所稱的文檔插入集合,我們使用 insert_one()
方法。
insert_one()
方法的第一個參數是字典,其中包含希望插入文檔中的每個字段名稱和值。
實例
在 "customers" 集合中插入記錄:
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] mydict = { "name": "Bill", "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) # 打印被插入文檔的 _id 值列表: 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) # 打印被插入文檔的 _id 值列表: print(x.inserted_ids)
- 上一頁 MongoDB 創建集合
- 下一頁 MongoDB Find