您现在的位置是:首页 > 编程开发 > Python > Python

如何在与python集成的mongoDB中编写自动操作

编辑:站长来源:网络整理作者: 未知2020-12-20Python

简介我创建了收集fee_details. { "_id": "fee_details","name": "Tution fees","student_total": 30,"fee_notpaid": 29,"fee_paid_by": [{ "stu_name": "jaya","date": "10-09-2014" }]} 我尝试使用以下查询输入fee_paid_by详细信息: db.fee_details.findAndMod

我创建了收集fee_details.

{
    "_id": "fee_details","name": "Tution fees","student_total": 30,"fee_notpaid": 29,"fee_paid_by": [{
    "stu_name": "jaya","date": "10-09-2014"
    }]
}

我尝试使用以下查询输入fee_paid_by详细信息:

db.fee_details.findAndModify({
    query: {
    "_id": "fee_details","fee_notpaid": {
        $gt: 0
    }
    },update: {
    $inc: {
        "fee_notpaid": -1
    },$push: {
        "fee_paid_by": {
            "stu_name": "jaya","date": "10-09-2014"
        }
    }
    }
})

它在命令行上执行,并将fee_paid_by细节添加到fee_details集合中.但我尝试在下面执行与python的查询集成

c = db.fee_details.find_and_modify({
    '$query': {
    "_id": "fee_details","fee_notpaid": {
        '$gt': 0
    }
    },'$update': {
    '$inc': {
        "fee_notpaid": -1
    },'$push': {
        "fee_paid_by": {
            "stu_name": s_name,"fee": fee
        }
    }
    }
})

当执行上面的代码时,它给出一个错误,要么必须删除或更新

输入fee_paid_by详细信息到fee_details收集的正确方法是什么?

提前致谢.

解决方法

.find_and_modify采用关键字参数,键名称不应以$sign开头.

>>> import pymongo
>>> client = pymongo.MongoClient()
>>> db = client.test
>>> col = db.collection
>>> name = 'jaya'
>>> fee = 11
>>> query = {'_id': 'free_details','free_notpaid': {'$gt':0}}
>>> update = {'$inc': {'free_notpaid': -1},'$push': {'free_paid_by': {'stu_name': name,'fee': fee}}}
>>> col.find_and_modify(query=query,update=update)

由于pymongo 3.0你应该使用find_one_and_delete(),find_one_and_replace()或find_one_and_update(),因此find_and_modify方法是DEPRECATED

>>> col.find_one_and_update(filter=query,update=update)

很赞哦! ()

点击排行

本栏推荐

猜你喜欢