ss1111
ss1111

Reputation: 249

Python - Removing a specific entry inside a document in MongoDB

I have the following entry in MongoDB. I am using PyMongo and I used the insert_one command to store this into the database:

{
    "_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"
        }
     ]
}

I want to insert a new date and price at the front and remove the last entry. This is the result I am looking for:

{
    "_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"
        }
     ]
}

My solution so far

I figured out how to insert an entry through python:

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

I'm having trouble with figuring out how to remove the last entry only. Could someone help me out with it?

Upvotes: 0

Views: 313

Answers (1)

A. Jesse Jiryu Davis
A. Jesse Jiryu Davis

Reputation: 24009

Follow the example for $push with $each. You can do something like this to push a new subdocument to the end of the array, then pop from the front of the array until its length is 3:

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

Upvotes: 2

Related Questions