mongodb的python访问_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}})

其它相关命令

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值