2016-11-24 139 views
2

收藏:更新文件

{ 
    "shopping_list": [ 
     { 
      "date": 22, 
      "drinks": [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000], 
      "year": 2016, 
      "month": 11 
     }, 
     { 
      "date": 23, 
      "drinks": [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000], 
      "year": 2016, 
      "month": 11 
     } 
    ], 
    "password": "user", 
    "date_signup": "10-11-2016", 
    "name": "User", 
    "email": "[email protected]" 
} 

我所做的代碼:

data_1 = [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000] 
data_2 = [2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000] 
con.update({"email": "[email protected]", 
      "shopping_list.date": 23, 
      "shopping_list.month": 11, 
      "shopping_list.year": 2016}, 
      {"$set": {"shopping_list.$.drinks": data_2}}) 

想這太(沒工作):

con.update({"email": "[email protected]", 
      "shopping_list.date": {"$eq": 23}, 
      "shopping_list.month": {"$eq": 11}, 
      "shopping_list.year": {"$eq": 2016}}, 
      {"$set": {"shopping_list.$.drinks": data_2}}) 

使用我的代碼,我使用$set將數組的第二個索引中的shopping_list作爲目標。但我運行後沒有任何變化。我的代碼有什麼問題?

回答

1

這是因爲您查詢表達式錯誤。

隨着您的查詢表達式$位置更新運算符標識要更新的文檔不知道該怎麼做。如果需要在嵌入式文檔上指定多個條件,則需要使用$elemMatch運算符。

con.update_one({ 
    "email": "[email protected]", 
    "shopping_list": { "$elemMatch": { 
     "date": 23,    
     "month": 11,    
     "year": 2016} 
    }}, 
    {"$set": {"shopping_list.$.drinks": data_2}}) 

另請注意,update()在MongoDB 3.2,3.0中已被棄用。你應該使用update_one()方法

+0

是的。這樣可行。謝謝。 – QuartZ