How to write an automatic operation in mongoDB integrated with python

I created a collection of fee_details.

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

I tried to enter data fee_paid_byusing the following query:

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

Runs on the command line and adds details fee_paid_byto the fee_details assembly. But I tried below request integration with 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
        }
    }
    }
})

when executing this above code it gives an error either must remove or update

What is the correct way to enter fee_paid_byparts in fee_detailsCollection

Thanks in advance.

+4
source share
1 answer

.find_and_modifyaccepts keyword arguments, and the key name should not start with a character $.

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

find_and_modify DEPRECATED pymongo 3.0 find_one_and_delete(), find_one_and_replace() find_one_and_update()

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

Source: https://habr.com/ru/post/1608662/


All Articles