2017-03-08 70 views
0

我在MongoDB中有以下條目。我使用PyMongo,我用的insert_one命令該存儲到數據庫中:Python - 在MongoDB中刪除文檔中的特定條目

{ 
    "_id" : ObjectId('ffffffffffffffffff'), 
    "Drink" : "Lemonade" 
    "Prices per dates" : [ 
     { 
      "Date" : "02-22-2017", 
      "Price" : "5.00" 
     }, 
     { 
      "Date" : "02-21-2017", 
      "Price" : "6.00" 
     },    
     { 
      "Date" : "02-20-2017", 
      "Price" : "7.00" 
     } 
    ] 
} 

我想插入在前面一個新的日期和價格,並刪除最後一個條目。這就是我要尋找的結果:

{ 
    "_id" : ObjectId('ffffffffffffffffff'), 
    "Drink" : "Lemonade" 
    "Prices per dates" : [ 
     { 
      "Date" : "02-23-2017", 
      "Price" : "4.00" 
     }, 
     { 
      "Date" : "02-22-2017", 
      "Price" : "5.00" 
     },    
     { 
      "Date" : "02-21-2017", 
      "Price" : "6.00" 
     } 
    ] 
} 

我的解決方案至今

我想通了如何將通過蟒蛇的條目:

db.collection.insert_one({"Drink":"Lemonade", "Prices per dates": { "Date" : "02-22-2017", "Price" : "5.00" }) 

我遇到的麻煩搞清楚如何只刪除最後一個條目。有人可以幫我解決嗎?

回答

2

關注the example for $push with $each。你可以做這樣的事情推一個新的子文檔到數組的結尾,然後從陣列前端彈出,直到其長度爲3:

db.collection.update_one(
    {"_id": _id}, 
    {'$push': { 
     'Prices per dates': { 
      '$each': [{ 
       "Date": "02-23-2017", 
       "Price": "4.00" 
      }], 
      '$slice': -3}}}) 
+0

我似乎得到一個錯誤:'$ slice'中美元($)前綴字段'$ slice'對存儲無效'。這是什麼意思? – ss1111

0

你可以試試下面的查詢在第一$position插入和$slice保留前三項。

db.collection.update_one({ 
    "_id": _id 
}, { 
    $push: { 
     "Prices per dates": { 
      $each: [{ 
       "Date": "02-23-2017", 
       "Price": "4.00" 
      }], 
      $position: 0, 
      $slice: 3 
     } 
    } 
})