2017-08-05 79 views
0

我試圖通過使用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

回答

1

{'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總是支持哈希的第一個元素和類型將是第二個。

相關問題