MongoDB pymongo模塊 插入數據

 

 

 

insert_one():spa

對一張不存在表插入數據,他會在插入數據同時自動生成數據表,code

 

例如我要對chat集合插入數據,插入一個空數據對象

 

import pymongo

mongo_client = pymongo.MongoClient(
    host='192.168.0.112',
    port=27017,
    username="admin",
    password="123456"
)

mongo_db = mongo_client["db1"]
# 插入數據
res = mongo_db.chat.insert_one({})
print(res,res.inserted_id)

 

 

返回對象blog

<pymongo.results.InsertOneResult object at 0x0000000002EDBF08>

 

 

 

 

inserted_id 獲取插入的數據的_id ObjectIdclass

 

5cb0ba3abd99392b1427c25e

 

 

> db.chat.find()
{ "_id" : ObjectId("5cb0ba3abd99392b1427c25e") }

 

 

 

 

insert_many() :插入多條數據import

import pymongo

mongo_client = pymongo.MongoClient(
    host='192.168.0.112',
    port=27017,
    username="admin",
    password="123456"
)

mongo_db = mongo_client["db1"]
# 插入數據
res = mongo_db.chat.insert_many(
    [
        {
            'name':"jack","age":13,
        },

        {
            'name':"mike","age":33,
        },
    ]
)
print(res,res.inserted_ids)

 

拿到對象cli

<pymongo.results.InsertManyResult object at 0x0000000002EDAF88>

 

inserted_ids 能夠返回多個插入的數據的 _id objectID
[ObjectId('5cb0bbf9bd993914d8b5d82c'), ObjectId('5cb0bbf9bd993914d8b5d82d')]
相關文章
相關標籤/搜索