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}})

其它相关命令

 

posted @ 2020-12-18 20:57  睁yan-ii  阅读(133)  评论(0编辑  收藏  举报