Python - 删除 MongoDB 文档中的特定条目
Python - Removing a specific entry inside a document in MongoDB
我在 MongoDB 中有以下条目。我正在使用 PyMongo,我使用 insert_one
命令将其存储到数据库中:
{
"_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"
}
]
}
我目前的解决方案
我想通了如何通过 python 插入条目:
db.collection.insert_one({"Drink":"Lemonade", "Prices per dates": { "Date" : "02-22-2017", "Price" : "5.00" } )
我无法弄清楚如何只删除最后一个条目。有人可以帮我解决吗?
关注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}}})
我在 MongoDB 中有以下条目。我正在使用 PyMongo,我使用 insert_one
命令将其存储到数据库中:
{
"_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"
}
]
}
我目前的解决方案
我想通了如何通过 python 插入条目:
db.collection.insert_one({"Drink":"Lemonade", "Prices per dates": { "Date" : "02-22-2017", "Price" : "5.00" } )
我无法弄清楚如何只删除最后一个条目。有人可以帮我解决吗?
关注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}}})