Python MongoDB 插入文档

Python MongoDB 插入文档

你可以使用 insert() 方法将文档存储到MongoDB。这个方法接受一个JSON文档作为参数。

语法

以下是insert方法的语法。

>db.COLLECTION_NAME.insert(DOCUMENT_NAME)

例子

> use mydb
switched to db mydb
> db.createCollection("sample")
{ "ok" : 1 }
> doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"}
{ "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
> db.sample.insert(doc1)
WriteResult({ "nInserted" : 1 })
>

同样地,你也可以使用 ** insert()** 方法插入多个文档。

> use testDB
switched to db testDB
> db.createCollection("sample")
{ "ok" : 1 }
> data = 
[
   {
      "_id": "1001", 
      "name": "Ram", 
      "age": "26", 
      "city": "Hyderabad"
   }, 
   {
      "_id": "1002", 
      "name" : "Rahim", 
      "age" : 27, 
      "city" : "Bangalore" 
   }, 
   {
      "_id": "1003", 
      "name" : "Robert", 
      "age" : 28, 
      "city" : "Mumbai" 
   }
]
[
   {
      "_id" : "1001",
      "name" : "Ram",
      "age" : "26",
      "city" : "Hyderabad"
   },
   {
      "_id" : "1002",
      "name" : "Rahim",
      "age" : 27,
      "city" : "Bangalore"
   },
   {
      "_id" : "1003",
      "name" : "Robert",
      "age" : 28,
      "city" : "Mumbai"
   }
]
> db.sample.insert(data)
BulkWriteResult
({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 3,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})
>

使用python创建一个集合

Pymongo提供了一个名为insert_one()的方法来在MangoDB中插入一个文档。在这个方法中,我们需要传递字典格式的文档。

例子

下面的例子在名为example的集合中插入了一个文档。

from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['mydb']

#Creating a collection
coll = db['example']

#Inserting document into a collection
doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"}
coll.insert_one(doc1)
print(coll.find_one())

输出

{
   '_id': ObjectId('5d63ad6ce043e2a93885858b'), 
   'name': 'Ram', 
   'age': '26', 
   'city': 'Hyderabad'
}

要使用pymongo向MongoDB插入多个文档,你需要调用insert_many()方法。

from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['mydb']

#Creating a collection
coll = db['example']

#Inserting document into a collection
data = 
[
   {
      "_id": "101", 
      "name": "Ram", 
      "age": "26", 
      "city": "Hyderabad"
   },
   {
      "_id": "102", 
      "name": "Rahim", 
      "age": "27", 
      "city": "Bangalore"
   },
   {
      "_id": "103", 
      "name": "Robert", 
      "age": "28", 
      "city": "Mumbai"
   }
]
res = coll.insert_many(data)
print("Data inserted ......")
print(res.inserted_ids)

输出

Data inserted ......
['101', '102', '103']

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程