pymongo批量增删改查

 

from mongoengine.connection import get_db, connect
from pymongo import MongoClient, ASCENDING, UpdateOne, InsertOne, DeleteOne, ReplaceOne
from pymongo.errors import BulkWriteError



# pymongo建立索引
client = MongoClient('120.xx.xx.xx:20002', username='xxx', password='xxxx')
db = client.annosys
image_db = db['image']
image_db.create_index([('image_id', ASCENDING)], unique=True)
image_index = sorted(list(image_db.index_information()))
print(image_index)

# pymongo批量插入和批量更新
mdb = MongoClient('120.xx.xx.xx:20002', username='xxx', password='xxxx')
db_name = mdb['db_name']

try:
    lines = [此处填写数据列表]
    image_batch = []
    pick_batch = []

    for idx, line in enumerate(lines):
        image_batch.append(UpdateOne(
            {'image_id': line.get("id")}, {
                '$set': {
                    'url': line.get("url"),
                    'width': line.get("width"),
                    'height': line.get("height")
                },
                '$addToSet': {
                    'datasets': line.get("dataset_id")
                }
            },
            upsert=True
        ))

        pick_batch.append(InsertOne(
            {'task_id': line.get("task_id"), 'image_id': line.get("id")}
        ))

        if idx % 2000 == 0:
            try:
                db_name['image'].bulk_write(image_batch)
                image_batch = []
                db_name['image_pick'].bulk_write(pick_batch)
                pick_batch = []
            except BulkWriteError as bwe:
                print("mongo error:", bwe.details)

    db_name['image'].bulk_write(image_batch)
    db_name['image_pick'].bulk_write(pick_batch)

except Exception as e:
    print("Exception:", e)


# pymongo批量查询
brand_images = mdb['goodlook']['brand_images'].find({"image_id": {"$in": image_ids}}) 
#image_ids是图片信息列表

# pymongo批量删除
brand_images = mdb['goodlook']['brand_images'].find({"image_id": {"$in": image_ids}}) 
mdb['goodlook']['brand_images'].remove({"image_id": {"$in": image_ids}})

# pymongo批量杂糅操作
requests = [InsertOne({'y': 1}), DeleteOne({'x': 1}),ReplaceOne({'w': 1}, {'z': 1}, upsert=True)]
result = db.test.bulk_write(requests)

  

转载于:https://www.cnblogs.com/adamans/articles/10492239.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python操作MongoDB的增删改查方法如下: 1. 连接MongoDB数据库 使用pymongo库连接MongoDB数据库,代码如下: ```python import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/") db = client["mydatabase"] ``` 2. 插入数据 使用insert_one()或insert_many()方法向MongoDB数据库中插入一条或多条数据,代码如下: ```python # 插入单条数据 mycollection = db["customers"] mydict = { "name": "John", "address": "Highway 37" } x = mycollection.insert_one(mydict) # 插入多条数据 mylist = [ { "name": "Amy", "address": "Apple st 652"}, { "name": "Hannah", "address": "Mountain 21"}, { "name": "Michael", "address": "Valley 345"}, { "name": "Sandy", "address": "Ocean blvd 2"}, { "name": "Betty", "address": "Green Grass 1"}, { "name": "Richard", "address": "Sky st 331"} ] x = mycollection.insert_many(mylist) ``` 3. 查询数据 使用find()方法查询MongoDB数据库中的数据,代码如下: ```python # 查询所有数据 for x in mycollection.find(): print(x) # 查询指定数据 myquery = { "address": "Park Lane 38" } mydoc = mycollection.find(myquery) for x in mydoc: print(x) ``` 4. 更新数据 使用update_one()或update_many()方法更新MongoDB数据库中的数据,代码如下: ```python # 更新单条数据 myquery = { "address": "Valley 345" } newvalues = { "$set": { "address": "Canyon 123" } } mycollection.update_one(myquery, newvalues) # 更新多条数据 myquery = { "address": { "$regex": "^S" } } newvalues = { "$set": { "name": "Minnie" } } x = mycollection.update_many(myquery, newvalues) ``` 5. 删除数据 使用delete_one()或delete_many()方法删除MongoDB数据库中的数据,代码如下: ```python # 删除单条数据 myquery = { "address": "Mountain 21" } mycollection.delete_one(myquery) # 删除多条数据 myquery = { "address": {"$regex": "^S"} } x = mycollection.delete_many(myquery) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值