1. 程式人生 > 實用技巧 >python 連線mongodb 使用

python 連線mongodb 使用

1 連線

import pymongo
mongo_client=pymongo.MongoClient(host='localhost',port=27017)
db=mongo_client.myip
table=db.myabac

 2 新增資料

table.insert( { item : "card", qty : 15 })

  插入指定 _id 欄位的文件,值 _id 必須在集合中唯一,以避免重複鍵錯誤,程式碼如下:

> table.insert(
    { _id: 10, item: "box", qty: 20 }
)
> table.find()
{ "_id" : 10, "item" : "box" , "qty": 20 }

 插入的多個文件無須具有相同的欄位。例如,下面程式碼中的第一個文件包含一個 _id 欄位和一個 type 欄位,第二個和第三個文件不包含 _id 欄位。因此,在插入過程中,MongoDB 將會為第二個和第三個文件建立預設 _id 欄位,程式碼如下:

db.test.insert(
    [
        { _id: 11, item: "pencil", qty: 50, type: "no.2" },
        { item: "pen", qty: 20 },
        { item: "eraser", qty: 25 }
    ]
)

  

查詢驗證,可以看到在 _id 插入期間,系統自動為第二、第三個文件建立了欄位,程式碼如下:

> table.find()
{ "_id" : 11, "item" : "pencil", "qty" : 50, "type" : "no.2" }
{ "_id" : Objectld("5bacf31728b746e917e06b27"), "item" : "pen", "qty" : 20 }
{ "_id" : Objectld("5bacf31728b746e917e06b28"), "item" : "eraser", "qty" : 25 }

 有序地插入多條文件的程式碼如下:

> table.insert([
        {_id:10, item:"pen", price:"20" },
        {_id:12, item:"redpen", price: "30" },
        {_id:11, item:"bluepen", price: "40" }
    ],
    {ordered:true}
)

  

 在設定 ordered:true 時,插入的資料是有序的,如果存在某條待插入文件和集合的某文件 _id 相同的情況,_id 相同的文件與後續文件都將不再插入。在設定 ordered:false 時,除了出錯記錄(包括 _id 重複)外其他的記錄繼續插入。

使用 insertOne() 插入一條文件的程式碼如下:

table.iusertone( { item: "card", qty: 15 } );

 使用 insertMany() 插入多條文件的程式碼如下:

table.insertMany([
    { item: "card", qty: 15 },
    { item: "envelope", qty: 20 },
    { item: "stamps", qty:30 }
]);

 給表新增有效期索引設定有效期間

table.create_index([("timer2", 1)], expireAfterSeconds=10)
from datetime import datetime
table.insert({"timer2": datetime.utcnow(), "user": "Hehehehe!"})

  

重建索引

(1)獲取所有索引

db.test.getIndexes()

(2)刪除所有索引
db.test.dropIndexes()

(3)更改索引過期時間

db.runCommand({collMod:"test",index:{keyPattern:{createdAt:1},expireAfterSeconds:0}})

其它相關命令