更新命令通过mongo shell工作,但不通过pymongo

更新命令通过mongo shell工作,但不通过pymongo

问题描述:

我试图通过使用pymongo来更新mongo文档中的数组,但它不起作用,但将相同的查询复制到robomongo的确行得通。 (它返回{'n': 1, 'nModified': 0, 'ok': 1.0, 'updatedExisting': True}更新命令通过mongo shell工作,但不通过pymongo

roboMongo:

db.my_collection.updateMany(
    {'start_time': 1501700400.0}, 
    {'$pull': {'related': {'$in': [{'KEY': '1', 'TYPE': 'my_type'}]}}}, 
    {upsert:true} 
) 

pymongo代码:

query_document = {'start_time': 1501700400.0} 
update_command = {'$pull': {'related': {'$in': [{'KEY': '1', 'TYPE': 'my_type'}]}}} 
_client[db][collection].update_many(query_document, update_command, True) 

文件:

{ 
    "_id" : ObjectId("598570c4ffd387293e368c8d"), 
    "related" : [ 
     { 
      "KEY" : "6", 
      "TYPE" : "my_type" 
     }, 
     { 
      "KEY" : "2", 
      "TYPE" : "my_type" 
     }, 
     { 
      "KEY" : "3", 
      "TYPE" : "my_type" 
     }, 
     { 
      "KEY" : "5", 
      "TYPE" : "my_type" 
     }, 
     { 
      "KEY" : "8", 
      "TYPE" : "my_type" 
     } 
    ], 
    "end_time" : 1501621200.0, 
    "start_time" : 1501700400.0 
} 

我想也许这是关系到“和” ?

有什么建议吗?

感谢

+0

pymongo电话的结果是什么?这是一个错误吗?或者它运行正常,但什么都不更新? – bagrat

+0

结果是:'{'n':1,'nModified':0,'ok':1.0,'updatedExisting':True}' –

+1

所以查询匹配文档,但不更改文档?是不是因为你正在尝试''pull''和'related'中的数组元素('“KEY”:“1”,...')?当你在robomongo中做这件事时会发生什么,并且你确定两个查询都是在相同版本的文档上进行操作的? – guessimtoolate

{'KEY': '1', 'TYPE': 'my_type'}要责令,所以我做强制命令:

ordered_relateds = [] 
for ptr in ptrs_to_remove: 
    ordered_ptrs.append(collections.OrderedDict(sorted(related.items(), key=lambda t: t[0]))) 

update_command = {"$pull": {"related": {"$in": ordered_related}}} 

这样KEY总是支持哈希的第一个元素和类型将是第二个。