我创建了收集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)